protected void doPost(final HttpServletRequest req, final HttpServletResponse resp) throws ServletException,IOException {
String fileName = "";
//boolean isMultipart = ServletFileUpload.isMultipartContent(req);
DiskFileItemFactory factory = new DiskFileItemFactory();
// Configure a repository (to ensure a secure temp location is used)
ServletContext servletContext = req.getSession().getServletContext();
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
System.out.println("-----------------uploading");
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");//解决中文乱码
try {
List<FileItem> items = upload.parseRequest(req);
for(FileItem item : items) {
//其他参数
String type = item.getContentType();
if(type == null) {
//System.out.println(item.getString(item.getFieldName()));
continue;
}
//文件参数
fileName = item.getName();
//设置保存文件路径
String realPath = this.getServletContext().getRealPath("/upload");
//System.out.println("-----------------realPath--"+realPath);
File dir = new File(realPath);
// System.out.println("-----------------filename--"+fileName);
if (!dir.exists() && !dir.isDirectory()) {
System.out.println(realPath+"目录不存在,需要创建");
//创建目录
dir.mkdir();
}
File f = new File(dir, fileName);
f.createNewFile();
//保存
item.write(f);
resp.getWriter().print("success");
}
}catch (FileUploadException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
本程序实现了点击按钮弹出选择上传文件的对话框,选定文件后,上传过程序中会有一个等待图片.gif 显示。
后出现问题,ajax里的data在带其他参数,后台接收不到,为NULL,需修改ajaxfileUpload.js文件,可参考
本文来自电脑杂谈,转载请注明本文网址:
http://www.pc-fly.com/a/ruanjian/article-52003-2.html
这也不能吃
一个省一艘
脱肛真的不要成本