@WebServlet("/uploadServlet2")
public class UploadServlet2 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//request.setCharacterEncoding("utf-8");
//获取文件名,得到后缀,然后通过uuid+后缀名得到一个新的文件名
//编写jspsmartupload代码
SmartUpload smartupload = new SmartUpload();
//初始化
smartupload.initialize(this.getServletConfig(),request,response);
try {
//上传
smartupload.upload();
} catch (SmartUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Request req = smartupload.getRequest();
System.out.println(req.getParameter("fileName"));
System.out.println(req.getParameter("name"));
Files files = smartupload.getFiles();//得到表单中的所有文件
System.out.println(files.getSize());//可以得到表单中上传文件的个数
System.out.println(files.getCount());
String path = this.getServletContext().getRealPath("./") +"upload\\";
System.out.println(path);
java.io.File fileDir = new java.io.File(path);
if(!fileDir.exists()) {
fileDir.mkdirs();
}
for(int i=0;i<files.getCount();i++) {
File file = files.getFile(i);
System.out.println(file.getFileName());
String fileName = file.getFileName();
String suffix = fileName.substring(fileName.lastIndexOf("."));
String newName = UUIDUtils.getUUID() + suffix;
System.out.println(newName);
// C:/sfsdfsd/sdfsd/webapps/JavaWeb14/
try {
file.saveAs(path+newName);
smartupload.save(path);
} catch (SmartUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}