JSP kết hợp HTML form tag cho phép user upload file lên server. File có thể là text, binary, image hoặc tài liệu bất kỳ.
Tạo Form Upload
Lưu ý quan trọng:
- Form method = POST (không dùng GET).
- Form enctype = multipart/form-data.
- Form action trỏ đến JSP xử lý backend (ví dụ uploadFile.jsp).
- Upload đơn: một <input type="file">. Upload nhiều: nhiều input với name khác nhau.
Ví dụ Form
<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 demo, cần triển khai backend để chạy.
JSP Backend (UploadFile.jsp)
Định nghĩa thư mục lưu file. 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>
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>");
}
%>
Thư viện cần: commons-fileupload.jar, commons-io.jar. Tạo thư mục c:\temp và c:\apache-tomcat5.5.29\webapps\data trước.
File upload thành công lưu tại c:\apache-tomcat5.5.29\webapps\data\.