upload.jsp
<%@ page contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>文件上传</title>
<script src="C:\Users\AKSJ\Desktop\JaveEEDay2\js\bootstrap-3.3.7-dist\js\jquery.min.js"></script>
</head>
<body>
<form action="${pageContext.servletContext.contextPath}/uploadServlet" name="one" enctype="multipart/form-data" method="post">
选择一个文件:
<input type="file" name="fileupload" value="upload" />
<input type="submit" value="上传">
</form>
</body>
</html>
upload.java
package abc;
import java.io.*;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.filefilter.SuffixFileFilter;
@WebServlet(name="CheckNameServlet",urlPatterns={"/uploadServlet"})
public class Upload extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String uploadpath = "";
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(30 * 1024);
factory.setRepository(factory.getRepository());
ServletFileUpload upload = new ServletFileUpload(factory);
List list = null;
try{
list = upload.parseRequest(request);
String[] limit = new String[]{".html", ".exe", ".jsp"};
SuffixFileFilter filter = new SuffixFileFilter(limit);
Iterator iterator = list.iterator();
while(iterator.hasNext()){
FileItem item =(FileItem)iterator.next();
if(!item.isFormField()){
String filePath = item.getName();
if(filePath != null){
File filename= new File(filePath);
File uploadFile = new File(request.getSession().getServletContext().getRealPath("/") + "upload");
uploadpath = uploadFile.getAbsolutePath()+File.pathSeparator + uploadpath;
uploadpath = uploadpath.substring(0, uploadpath.length()-1);
File saveFile = new File(uploadpath,filename.getName());
boolean flag = filter.accept(saveFile);
if(flag){
out.print("禁止上传此类型的文件");
break;
}else{
try {
item.write(saveFile);
out.print("文件上传成功");
} catch (Exception e) {
out.print("文件上传失败了");
e.printStackTrace();
}
}
}
}
}
}catch(Exception e){
e.printStackTrace();
}
}
}
运行结果: