servlet 文件上传简易版

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);
}

}

上一篇:.net webapi 接收 xml 格式数据的三种情况


下一篇:原生JS中apply()方法的一个值得注意的用法