1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134
| package my.fileUpload;
import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator; import org.apache.commons.fileupload.FileItemStream; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.fileupload.util.Streams; import org.json.JSONObject;
public class FileUploadServer extends HttpServlet {
File tmpDir;//文件保存的临时目录
@Override public void init() throws ServletException { System.out.println("初始化"); File webRoot = new File(getServletContext().getRealPath("/")); tmpDir = new File(webRoot , "upload"); if(!tmpDir.exists()) tmpDir.mkdirs(); }
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request , response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("进入"); int error = 0; String reason = "OK"; String data = null; try { data = doUpload(request , response); } catch (Exception e) { error = -1; reason = e.getMessage(); // TODO Auto-generated catch block e.printStackTrace(); }
JSONObject jreq = new JSONObject(); jreq.put("error", error); jreq.put("reason", reason); if(data != null) jreq.put("data", data); response.setCharacterEncoding("utf-8"); response.setContentType("text/plain"); PrintWriter out = response.getWriter(); out.write(jreq.toString(2));
}
private String doUpload(HttpServletRequest request, HttpServletResponse response) throws Exception { String result = null; boolean isMultipart = ServletFileUpload.isMultipartContent(request); if(!isMultipart) throw new Exception("请求编码必须为: multipart/form-data !"); request.setCharacterEncoding("utf-8"); ServletFileUpload upload = new ServletFileUpload(); FileItemIterator iter = upload.getItemIterator(request); while(iter.hasNext()) { //表单域 FileItemStream item = iter.next(); String fieldName = item.getFieldName(); InputStream fieldStream = item.openStream(); if(item.isFormField()) { //普通表单域直接读取 String fieldValue = Streams.asString(fieldStream , "utf-8"); System.out.println("表单域:" + fieldName + "=" + fieldValue); } else { String realName = item.getName();//原始文件名 //文件的后缀名 String suffix = realName.substring(realName.lastIndexOf(".")+1); System.out.println("文件名:" + realName + "....." + "后缀名:" + suffix);
//创建已个临时文件名 String s = UUID.randomUUID().toString(); String s2 = s.substring(0,8)+s.substring(9,13)+s.substring(14,18)+s.substring(19,23)+s.substring(24); s2 = s2.toUpperCase(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd-HHmmss"); String dateStr = sdf.format(new Date()); String fileName = dateStr +"-" + s2 + "." + suffix; result = fileName; System.out.println("文件名:" + fileName); File file = new File(tmpDir , fileName); long fileSsize = 0;//文件大小 System.out.println("===========文件开始上传============="); //从FieldStream读取数据,保存到目标文件 file.getParentFile().mkdirs(); FileOutputStream fileStream = new FileOutputStream(file); try { byte[] buf = new byte[1024]; while(true) { int n = fieldStream.read(buf); if(n < 0) break; if(n == 0) continue; fileStream.write(buf, 0, n);
fileSsize += n; } }finally { fileStream.close(); fieldStream.close(); } System.out.println("上传完成!");
} } return result; } }
|