Skip to content

Instantly share code, notes, and snippets.

@deluxebear
Created April 3, 2013 16:21
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save deluxebear/5302725 to your computer and use it in GitHub Desktop.
Save deluxebear/5302725 to your computer and use it in GitHub Desktop.
Servlet 3实现文件上传
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
/**
* Servlet 3 实现文件上传
*/
@WebServlet("/UploadServlet")
@MultipartConfig(fileSizeThreshold=1024*1024*2, // 2MB 当数据量大于该值时,内容将被写入文件
maxFileSize=1024*1024*10, // 10MB 允许上传的文件最大值。默认值为 -1,表示没有限制
maxRequestSize=1024*1024*50) // 50MB 针对该 multipart/form-data 请求的最大数量,默认值为 -1,表示没有限制
public class UploadServlet extends HttpServlet {
/**
* Name of the directory where uploaded files will be saved, relative to
* the web application directory.
*/
private static final String SAVE_DIR = "uploadFiles";
/**
* handles file upload
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// gets absolute path of the web application
String appPath = request.getServletContext().getRealPath("");
// constructs path of the directory to save uploaded file
String savePath = appPath + File.separator + SAVE_DIR;
// creates the save directory if it does not exists
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
part.write(savePath + File.separator + fileName);
}
request.setAttribute("message", "Upload has been done successfully!");
getServletContext().getRequestDispatcher("/message.jsp").forward(
request, response);
}
/**
* 从 HTTP header content-disposition中获得文件名
* content-disposition中内容:form-data; name="dataFile"; filename="PHOTO.JPG"
*/
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length()-1);
}
}
return "";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment