Skip to content

Upload file #3

@tranquangtanqt

Description

@tranquangtanqt

Ở file jsp sẽ có một thẻ input để chọn file

<form action="add" method="post" enctype="multipart/form-data" class="form-horizontal">
     <div class="form-group">
          <label class="form-control-label">Chọn ảnh</label>
          <div>
               <input type="file" name="file" id="profile-img"> 
               <img src="" id="profile-img-tag" width="500px" style="display: block; margin-left: auto; margin-right: auto;" />
          </div>
     </div>
</form>

Trong servlet:

  • Khai báo MultipartConfig
@WebServlet(description = "Add Product", urlPatterns = { "/add" })
@MultipartConfig(fileSizeThreshold = 1024 * 1024 * 2, // 2MB
		maxFileSize = 1024 * 1024 * 50, // 50MB
		maxRequestSize = 1024 * 1024 * 50) // 50MB
  • Cài đặt doPost
protected void doPost(HttpServletRequest request, HttpServletResponse response)
		throws ServletException, IOException {
	request.setCharacterEncoding("UTF-8");
	response.setCharacterEncoding("UTF-8");
	response.setContentType("text/html; charset=UTF-8");

	String empty = new String();

        //Lấy dữ liệu từ thẻ input của jsp (<input type="file" name="file" id="profile-img"> )
	Part filePart = request.getPart("file");
       //Lấy tên file
	String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString().trim();
	InputStream fileContent = filePart.getInputStream();

	if (!fileName.equals(empty)) {
                //Nếu thẻ input trong jsp có file thì đặt lại tên mới để khỏi trùng
		fileName = new Date().getTime() + fileName;

		// Đường dẫn tuyệt đối tới thư mục gốc của web app.
		String appPath = request.getServletContext().getRealPath("");
		appPath = appPath.replace('\\', '/');

		// Thư mục để lưu file tải lên.
		String fullSavePath = null;
		if (appPath.endsWith("/")) {
			fullSavePath = appPath + "assets/img/shop/product/";
		} else {
			fullSavePath = appPath + "/" + "assets/img/shop/product/";
		}

		File file = new File(fullSavePath, fileName);
//		System.out.println(file.getPath());

		try {
                        //Lưu file
			Files.copy(fileContent, file.toPath());
		} catch (Exception e) {
                       //Lưu thất bại
		}
	}
	//Nội dung cần lấy sau đưa vào csdl chính là fileName.

Muốn show file (ở đây là file ảnh) trong file jsp chỉ cần kiểm tra giá trị của tên ảnh có rỗng hay không là được

<%
      if (l.getAnhchinh() != "") {
%> 
<img alt="" src="../../../assets/img/shop/product/<%=l.getAnhchinh()%>"> 
<%
 	} else {
 %> 
<img alt="" src="https://placehold.it/270x270"> 
<%
 	}
 %>

Với l.getAnhchinh(): là một giá trị của file ảnh. (tên file ảnh)

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions