import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
/**
* Servlet implementation class uploadservlet
*/
@WebServlet("/upload")
public class uploadservlet extends HttpServlet {
@Override
protected void service(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
// TODO Auto-generated method stub
String mess="";
//上传位置目标路径
String basePath="D://upload";
//创建工厂,
DiskFileItemFactory dfIF=new DiskFileItemFactory();
//
ServletFileUpload sf=new ServletFileUpload(dfIF);
//
sf.setHeaderEncoding("UTF-8");
//判断表单是否为上传文件
if (!ServletFileUpload.isMultipartContent(arg0)) {
return;
}
try {
//把每一个input 封装成一个items 形成集合
List<FileItem>items= sf.parseRequest(arg0);
//是否是普通input
for (FileItem fileItem : items) {
if (fileItem.isFormField()) {
String name=fileItem.getFieldName();
String value=fileItem.getString("utf-8");
System.out.println(name+":"+value);
}
else {
//如果上传文件为空
String filename=fileItem.getName();//获取上传文件的文件名
if (filename==null||filename.equals("")) {
//跳过file的input接着遍历其他input
continue;
}
//文件上传
InputStream is= fileItem.getInputStream();
FileOutputStream fos=new FileOutputStream(basePath+"/"+filename);
byte[] buffer=new byte[1024];
int len=0;
while((len=is.read(buffer))!=-1){
fos.write(buffer, 0, len);
}
is.close();
fos.close();
fileItem.delete();
mess="成功上传";
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
mess="上传失败";
}
arg0.setAttribute("mess", mess);
}
}
继承HttpServlet类后 实现service方法
其中
DiskFileItemFactory工厂 为了判断传过来的input标签是否为普通标签
if (!ServletFileUpload.isMultipartContent(arg0)) {
return;
}
该语句是如果传过来的参数不是文件类型,那么返回不继续执行
上传时是根据定义的文件目录上传