JSP kết hợp với HTML form tag cho phép user upload file lên server. File upload có thể là text, binary, image hoặc bất kỳ tài liệu nào.
Tạo Form Upload File
Điểm quan trọng:
- Form method phải là POST, không dùng GET.
- Form enctype phải là multipart/form-data.
- Form action trỏ đến file JSP xử lý upload backend (ví dụ uploadFile.jsp).
- Upload đơn: một thẻ <input type="file">. Upload nhiều: nhiều input với name khác nhau.
Ví dụ Form HTML
<html>
<head> <title>File Uploading Form</title> </head>
<body>
<h3>File Upload:</h3>
Select a file to upload: <br />
<form action="UploadServlet" method="post" enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
</form>
</body>
</html>
Lưu ý: Form trên chỉ demo, không chạy được nếu không triển khai backend.
Viết JSP Backend
Định nghĩa vị trí lưu file upload. Có thể hard-code hoặc dùng context-param trong web.xml:
<web-app>
<context-param>
<description>Location to store uploaded file</description>
<param-name>file-upload</param-name>
<param-value>c:\apache-tomcat-5.5.29\webapps\data\</param-value>
</context-param>
</web-app>
Source code UploadFile.jsp (xử lý multiple files):
<%@ page import = "java.io.*,java.util.*, javax.servlet.*" %>
<%@ page import = "javax.servlet.http.*" %>
<%@ page import = "org.apache.commons.fileupload.*" %>
<%@ page import = "org.apache.commons.fileupload.disk.*" %>
<%@ page import = "org.apache.commons.fileupload.servlet.*" %>
<%@ page import = "org.apache.commons.io.output.*" %>
<%
File file;
int maxFileSize = 5000 * 1024;
int maxMemSize = 5000 * 1024;
ServletContext context = pageContext.getServletContext();
String filePath = context.getInitParameter("file-upload");
String contentType = request.getContentType();
if ((contentType.indexOf("multipart/form-data") >= 0)) {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(maxMemSize);
factory.setRepository(new File("c:\\temp"));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxFileSize);
try {
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
out.println("<html><head><title>JSP File upload</title></head><body>");
while (i.hasNext()) {
FileItem fi = (FileItem)i.next();
if (!fi.isFormField()) {
String fieldName = fi.getFieldName();
String fileName = fi.getName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
} else {
file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")+1));
}
fi.write(file);
out.println("Uploaded Filename: " + filePath + fileName + "<br>");
}
}
out.println("</body></html>");
} catch(Exception ex) { System.out.println(ex); }
} else {
out.println("<html><head><title>Servlet upload</title></head><body><p>No file uploaded</p></body></html>");
}
%>
Yêu cầu thư viện:
- commons-fileupload.x.x.jar (tải từ https://commons.apache.org/fileupload/)
- commons-io-x.x.jar (tải từ https://commons.apache.org/io/)
Tạo trước thư mục c:\temp và c:\apache-tomcat5.5.29\webapps\data. Upload file kích thước < maxFileSize.
File upload thành công sẽ nằm trong c:\apache-tomcat5.5.29\webapps\data\.