码迷,mamicode.com
首页 > Web开发 > 详细

servlet 文件上传简易版

时间:2016-08-25 14:29:04      阅读:234      评论:0      收藏:0      [点我收藏+]

标签:

package cn.itcast.servlet;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadFile extends HttpServlet{
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
//存放文件的真实路径
String path = request.getRealPath("/upload");

factory.setRepository(new File(path));
//文件的大小
factory.setSizeThreshold(1024 * 1024);

ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");

try{
List<FileItem> list =(List<FileItem>) upload.parseRequest(request);

for(FileItem item : list){
String name = item.getFieldName();
if(item.isFormField()){
String value = item.getString();

System.out.println(name + "=" + value);
request.setAttribute(name, value);
}else{
String value = item.getName();
int start = value.lastIndexOf("\\");
String filename = value.substring(start + 1);

request.setAttribute(name, filename);

item.write(new File(path,filename));
}
}
}catch(Exception e){
e.printStackTrace();
}

request.getRequestDispatcher("uploadResult.jsp").forward(request, response);
}

}

servlet 文件上传简易版

标签:

原文地址:http://www.cnblogs.com/wxm-bk/p/5806613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!