package cn.autoform.web.controller.resumable; import cn.autoform.bean.ExcelLog; import cn.autoform.fw.exception.FormClientException; import cn.autoform.fw.exception.IEMRuntimeException; import cn.autoform.fw.exception.RestResult; import cn.autoform.fw.utility.RestResultGenerator; import cn.autoform.util.tool.JSONTool; import cn.autoform.web.client.FormClient; import cn.autoform.web.client.bean.Enclosure; import cn.autoform.web.controller.resumable.redis.CacheTool; import cn.autoform.web.controller.resumable.util.*; import cn.autoform.web.service.Enclosure.EnclosureService; import com.mysql.jdbc.StringUtils; import org.apache.commons.io.IOUtils; import org.csource.common.MyException; import org.csource.fastdfs.StorageClient1; import org.csource.fastdfs.TrackerServer; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; import javax.annotation.Resource; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.FileOutputStream; import java.io.IOException; import java.io.Serializable; import java.util.*; import java.util.concurrent.TimeoutException; @RestController public class UploadAccessotyController { @Resource(name="redisCache") private CacheTool redisCache; @Autowired private EnclosureService enclosureService; @Autowired private FormClient formClient; List format = Arrays.asList("gif","png","jpg","pdf","xls","xlsx","doc","docx"); /** * 上传附件 * @param request * @param response * @throws IOException * @throws MyException * @throws ServletException */ @RequestMapping(value = "${request.upload1}", method = RequestMethod.POST) public void doPost(HttpServletRequest request,HttpServletResponse response) throws IOException, MyException, ServletException { int resumableChunkNumber = getResumableChunkNumber(request); System.out.println("number:"+resumableChunkNumber); ResumableInfo info = getResumableInfo(request); //需要上传得文件 MultipartFile file; //上传文件的name和格式 String fileName; //上传文件的name; String name = null; //一个流 //InputStream is; //连接池 TrackerServer tServer; //主线程 StorageClient1 client = null; System.out.println("获取连接"); tServer = LocalCloudUploadUtil.getTrackerServerInstance(); client = LocalCloudUploadUtil.connect(tServer); System.out.println("client:"+JSONTool.toJson(client)); //取到上传的文件 file = getFile(request); //取到流 //is = getInputStream(request); FormClientException f =new FormClientException(); info.uploadedChunks.add(new ResumableInfo.ResumableChunkNumber(resumableChunkNumber)); fileName = file.getOriginalFilename(); byte[] filebuff = file.getBytes(); //判断文件格式正确 if(fileName.indexOf('.') != -1) { //截取上传文件的的name name = fileName.substring(fileName.lastIndexOf('.')+1); System.out.println("文件名:"+name); String gs = fileName.substring(fileName.lastIndexOf('.')+1,fileName.length()); System.out.println("当前格式:"+gs); String gs1 =format.stream().filter(o->Objects.equals(o,gs)).findFirst().orElse(null); if(gs1 == null || Objects.equals("",gs1)){ throw new IEMRuntimeException("C00023"); } } String appender_file_id = redisCache.get(info.resumableFilename, String.class); if(appender_file_id != null && !Objects.equals("",appender_file_id)) { String gs3 = fileName.substring(fileName.lastIndexOf('.')+1, fileName.length()); String gs4 = format.stream().filter(o -> Objects.equals(o, gs3)).findFirst().orElse(null); if (gs4 == null || Objects.equals("",gs4)) { System.out.println("上传后文件名:"+appender_file_id); f.setCode("C00023"); f.setName("上传格式不支持!"); throw f; } } System.out.println("元素ID:"+appender_file_id); if(StringUtils.isNullOrEmpty(appender_file_id)) { //分块上传 System.out.println("进入1"); appender_file_id = client.upload_appender_file1(filebuff, name, null); redisCache.delete(info.resumableFilename); redisCache.add(info.resumableFilename, appender_file_id); } else { System.out.println("进入2"); client.append_file1(appender_file_id, filebuff); } info.uploadedChunks.add(new ResumableInfo.ResumableChunkNumber(resumableChunkNumber)); String name1 = info.checkIfUploadFinished(); response.setCharacterEncoding("UTF-8"); if (!CheckUtil.checkEmpty(name1)) { //Check if all chunks uploaded, and change filename ResumableInfoStorage.getInstance().remove(info); redisCache.delete(info.resumableFilename); response.getWriter().print(appender_file_id); } else { response.getWriter().print("Upload"); } } /** * 上传处理-取出上传文件 */ public MultipartFile getFile(HttpServletRequest request){ CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( request.getSession().getServletContext()); if(multipartResolver.isMultipart(request)){ MultipartHttpServletRequest multiRequest; multiRequest = (MultipartHttpServletRequest) request; //取出上传文件的名称(input[file]的name) Iterator names = multiRequest.getFileNames(); while (names.hasNext()) { String name = names.next(); System.out.println("文件名:"+name); // 根据name值拿取文件 MultipartFile file = multiRequest.getFile(name); return file; } } return null; } /** * 返回上传进度 * @param request * @param response * @throws ServletException * @throws IOException */ @RequestMapping(value = "/upload/doget", method = RequestMethod.GET) protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int resumableChunkNumber = getResumableChunkNumber(request); ResumableInfo info = getResumableInfo(request); if (info.uploadedChunks.contains(new ResumableInfo.ResumableChunkNumber(resumableChunkNumber))) { response.getWriter().print("Uploaded."); //This Chunk has been Uploaded. } else { // response.setStatus(HttpServletResponse.SC_NOT_FOUND); response.setStatus(HttpServletResponse.SC_NO_CONTENT); } } /** * 上传处理-取出input流 */ // public InputStream getInputStream(HttpServletRequest request){ // CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver( // request.getSession().getServletContext()); // if(multipartResolver.isMultipart(request)){ // MultipartHttpServletRequest multiRequest; // multiRequest = (MultipartHttpServletRequest) request; // //取出上传文件的名称(input[file]的name) // Iterator names = multiRequest.getFileNames(); // while (names.hasNext()) { // String name = names.next(); // // 根据name值拿取文件 // MultipartFile file = multiRequest.getFile(name); // try{ // return file.getInputStream(); // }catch(IOException e){ // e.printStackTrace(); // } // } // } // return null; // } private int getResumableChunkNumber(HttpServletRequest request) { return HttpUtils.toInt(request.getParameter("resumableChunkNumber"), -1); } /** * 取出相关参数 * @param request * @return * @throws IOException * @throws ServletException */ private ResumableInfo getResumableInfo(HttpServletRequest request) throws IOException, ServletException { //断点大小 int resumableChunkSize = HttpUtils.toInt(request.getParameter("resumableChunkSize"), -1); //文件大小 long resumableTotalSize = HttpUtils.toLong(request.getParameter("resumableTotalSize"), -1); String resumableIdentifier = request.getParameter("resumableIdentifier"); //文件名 String resumableFilename = new String(request.getParameter("resumableFilename").getBytes("iso-8859-1"), "utf-8"); String resumableRelativePath = new String(request.getParameter("resumableRelativePath").getBytes("iso-8859-1"), "utf-8"); System.out.println("resumableChunkSize:"+resumableChunkSize+" resumableTotalSize:"+resumableTotalSize+" resumableTotalSize:"+resumableTotalSize+" resumableFilename:"+resumableFilename+" resumableRelativePath:"+resumableRelativePath); ResumableInfoStorage storage = ResumableInfoStorage.getInstance(); ResumableInfo info = storage.get(resumableChunkSize, resumableTotalSize, resumableIdentifier, resumableFilename, resumableRelativePath, ""); if (!info.vaild()) { storage.remove(info); throw new ServletException("Invalid request params."); } return info; } //下载 @RequestMapping(value="${request.upload2}", method = RequestMethod.POST) public void DownloadFile(@RequestBody Map map) { try { TrackerServer tServer; //主线程 StorageClient1 client = null; //获取连接 tServer = LocalCloudUploadUtil.getTrackerServerInstance(); client = LocalCloudUploadUtil.connect(tServer); //卷名,文件名暂时写死 byte[] b = client.download_file("group1", "M00/00/00/wKgfsFoZPn6EbP_mAAAAAOdA9NY114.txt"); //下载地址暂时写死 IOUtils.write(b, new FileOutputStream("D:\\表格.txt")); } catch (Exception e) { e.printStackTrace(); } } /** * 删除文件 */ @RequestMapping(value="${request.upload3}", method = RequestMethod.POST) public RestResult deleteFile(@RequestBody Enclosure enc){ System.out.println("参数"+JSONTool.toJson(enc)); System.out.println(JSONTool.toJson(enc)); String path = enc.getPhysicsFileName(); if(path != null && !path.equals("")){ try { int ab = path.indexOf("/"); String volumn = path.substring(0, ab); String filePath = path.substring(ab+1, path.length()); TrackerServer tServer; //主线程 StorageClient1 client = null; //获取连接 tServer = LocalCloudUploadUtil.getTrackerServerInstance(); client = LocalCloudUploadUtil.connect(tServer); int y = 0; int i = 0; //fastdfs BUG 两次访问才能删除 do{ y++; i = client.delete_file(volumn, filePath); System.out.println(i+"访问"+y); }while(i==0); //删除数据表中数据 System.out.println("删除的数据"+i); if(i>0){ enclosureService.deleteFile(path); } return RestResultGenerator.genSuccessResult(i); } catch (Exception e) { e.printStackTrace(); } } return RestResultGenerator.genSuccessResult(-1); } @RequestMapping(value = "/resumable/excel", method = RequestMethod.POST) public RestResult uploadExcel(HttpServletRequest request,HttpServletResponse response) throws IOException, MyException, ServletException, TimeoutException { MultipartFile file; String id = request.getParameter("id"); ExcelLog excelLog = new ExcelLog(); excelLog.setId(Integer.parseInt(id)); String filePath = null; try { file = getFile(request); String fileName = file.getOriginalFilename(); byte[] filebuffer = file.getBytes(); TrackerServer tServer; //主线程 StorageClient1 client = null; //获取连接 tServer = LocalCloudUploadUtil.getTrackerServerInstance(); client = LocalCloudUploadUtil.connect(tServer); //卷名,文件名暂时写死 filePath = client.upload_file1(filebuffer ,fileName.substring(fileName.lastIndexOf('.')+1),null); } catch (Exception e) { e.printStackTrace(); } excelLog.setState(2); excelLog.setMag("导出成功"); excelLog.setOverTime(new Date()); excelLog.setFilePath(filePath); Object o = formClient.updateExcelLog(excelLog); System.out.println("上传成功:"+filePath); System.out.println("修改状态返回结果为:"+ JSONTool.toJson(o)); return RestResultGenerator.genSuccessResult(Integer.parseInt(Objects.toString(o,"-1"))); } public static void main(String[] args) { UploadAccessotyController c = new UploadAccessotyController(); c.c(); } public void c(){ Map> m = new HashMap<>(); m.put("1",Arrays.asList("a","b", "1")); m.put("2",Arrays.asList("c","d")); m.put("3",Arrays.asList("e","f")); m.put("4",Arrays.asList("g","h")); Collection> L = m.values(); List list = new ArrayList<>(); Map> ms = new HashMap<>(); for(List ls:L){ if(list.size()==0) { ls.stream().forEach(o -> list.add(o)); ms.put("1",list); }else{ List list1 = new ArrayList<>(); ms.get("1").stream().forEach(o1-> ls.stream().forEach(o2->list1.add(o1+o2)) ); System.out.println(JSONTool.toJson(list1)); ms.put("1",list1); } } } }