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
| 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.FileUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.util.List;
@Controller public class UploadController { private final static String utf8 = "utf-8";
@RequestMapping("/upload") @ResponseBody public void upload(HttpServletRequest req, HttpServletResponse res) throws Exception {
res.setCharacterEncoding(utf8); Integer schunk = null; Integer schunks = null; String name = null; String uploadPath = "F:\\fileItem"; BufferedOutputStream os = null; try { DiskFileItemFactory factory = new DiskFileItemFactory(); factory.setSizeThreshold(1024); factory.setRepository(new File(uploadPath)); ServletFileUpload upload = new ServletFileUpload(factory); upload.setFileSizeMax(51 * 10241 * 10241 * 10241); upload.setSizeMax(101 * 10241 * 10241 * 10241); List<FileItem> items = upload.parseRequest(req);
for (FileItem item : items) { if (item.isFormField()) { if ("chunk".equals(item.getFieldName())) { schunk = Integer.parseInt(item.getString(utf8)); } if ("chunks".equals(item.getFieldName())) { schunks = Integer.parseInt(item.getString(utf8)); } if ("name".equals(item.getFieldName())) { name = item.getString(utf8); } } }
for (FileItem item : items) { if (!item.isFormField()) { String temFileName = name; if (name != null) { if (schunk != null) { temFileName = schunk + "_" + name; } File temFile = new File(uploadPath, temFileName); if (!temFile.exists()) { item.write(temFile); } } } } if (schunk != null && schunk.intValue() == schunks.intValue()-1) { File tempFile = new File(uploadPath, name); os = new BufferedOutputStream(new FileOutputStream(tempFile)); for (int i = 0; i < schunks; i++) { File file = new File(uploadPath, i + "_" + name); while (!file.exists()) { Thread.sleep(100); } byte[] bytes = FileUtils.readFileToByteArray(file); os.write(bytes); os.flush(); file.delete(); } os.flush(); } res.getWriter().write("上传成功"); }finally { try { if (os != null) { os.close(); } }catch (IOException e) { e.printStackTrace(); } } } }
|