uploadFile(@RequestBody String jsonStr, HttpServletRequest request, HttpServletResponse response) { //创建封装的返回对象 Result> result = new Result<>(); //将请求的参数转为JSONObject对象 JSON_使用httpurlconnection发送单">
赞
踩
@PostMapping(value = "/uploadFile") public Result<?> uploadFile(@RequestBody String jsonStr, HttpServletRequest request, HttpServletResponse response) { //创建封装的返回对象 Result<?> result = new Result<>(); //将请求的参数转为JSONObject对象 JSONObject jsonObj = JSONObject.parseObject(jsonStr); //获取到相应的请求参数 String orderId = String.valueOf(jsonObj.get("orderId")); String type = String.valueOf(jsonObj.get("type")); //解析请求的附件列表转为JSONArray JSONArray json = JSONArray.parseArray(String.valueOf(jsonObj.get("fileList"))); //定义返回的提示 String resultVal = "上传成功"; //获取另一个项目需要接收附件的地址 RequestBaseUrl info = requestBaseUrlService.getInfo(); //拼接地址和基础的请求参数(参数中不能出现中文,否则报错) String actionUrl = info.getUrl3() + "/predictOrderController.do?fileReceive&orderno=" + orderId + "&type=" + type; //循环JSONArray for (Object o : json) { Map<String, File> files = new HashMap<String, File>(); //强转发为map Map map = (Map)o; //得到文件地址 String filePath = uploadpath + File.separator + map.get("filePath").toString(); File file = new File(filePath); //判断文件是否存在 if(!file.exists()){ response.setStatus(404); result.setMessage("保存失败"); result.setSuccess(false); throw new RuntimeException("文件不存在.."); } else { files.put(file.getName(), file); } try { //调用附件传输方法,得到返回值 resultVal = upLoadFilePost(actionUrl, files); //判断结果,接收附件接口返回的是Boolean也会被转为String类型,所以使用equals判断即可 if("true".equals(resultVal)) { //删除附件(这里可删可不删) file.delete(); } else { resultVal = "上传失败"; result.setSuccess(false); } } catch (Exception e) { e.printStackTrace(); } } result.setMessage(resultVal); return result; }
public String upLoadFilePost(String actionUrl, Map<String, File> files) throws IOException { String BOUNDARY = java.util.UUID.randomUUID().toString(); String PREFIX = "--", LINEND = "\r\n"; String MULTIPART_FROM_DATA = "multipart/form-data"; String CHARSET = "UTF-8"; URL uri = new URL(actionUrl); HttpURLConnection conn = (HttpURLConnection) uri.openConnection(); conn.setReadTimeout(15 * 1000); conn.setDoInput(true);// 允许输入 conn.setDoOutput(true);// 允许输出 conn.setUseCaches(false); conn.setRequestMethod("POST"); // Post方式 conn.setRequestProperty("connection", "keep-alive"); conn.setRequestProperty("Charsert", "UTF-8"); conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA + ";boundary=" + BOUNDARY); DataOutputStream outStream = new DataOutputStream( conn.getOutputStream()); // 发送文件数据 if (files != null) for (Map.Entry<String, File> file : files.entrySet()) { StringBuilder sb1 = new StringBuilder(); sb1.append(PREFIX); sb1.append(BOUNDARY); sb1.append(LINEND); sb1.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getKey() + "\"" + LINEND); sb1.append("Content-Type: application/octet-stream; charset=" + CHARSET + LINEND); sb1.append(LINEND); outStream.write(sb1.toString().getBytes("utf-8")); //getBytes()不加utf-8 传输中文名附件时,接收附件的地方解析文件名会乱码 InputStream is = new FileInputStream(file.getValue()); byte[] buffer = new byte[1024]; int len = 0; while ((len = is.read(buffer)) != -1) { outStream.write(buffer, 0, len); } is.close(); outStream.write(LINEND.getBytes()); } // 请求结束标志 byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes(); outStream.write(end_data); outStream.flush(); // 得到响应码 int res = conn.getResponseCode(); if (res == 200) { InputStream in = conn.getInputStream(); InputStreamReader isReader = new InputStreamReader(in); BufferedReader bufReader = new BufferedReader(isReader); String line = ""; String data = ""; while ((line = bufReader.readLine()) != null) { data += line; } outStream.close(); conn.disconnect(); return data; } //关闭流 outStream.close(); //关闭连接 conn.disconnect(); return null; }
@RequestMapping(params="fileReceive") @ResponseBody public Boolean fileInteraction(HttpServletRequest request, HttpServletResponse response) throws Exception { Boolean result = false; MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; //解析request,将结果放置在list中 Map<String, List<MultipartFile>> fileMap = multiRequest.getMultiFileMap(); for (String key : fileMap.keySet()) { List<MultipartFile> files = fileMap.get(key); for (MultipartFile file : files) { if (!file.isEmpty()) { String fileNamePath = file.getOriginalFilename(); String[] params = fileNamePath.split("\\."); String filename = ""; int i = 0; for (String str : params) { i = i + 1; if (StringUtils.isNotEmpty(filename)) { if (i==params.length) { filename = filename + "." + str; }else{ filename = filename + "/" + str; } }else{ filename = str; } } // 文件保存路径 String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/wxfile/" + filename; System.out.println(filePath); File iFile = new File(filePath); File iFileParent = iFile.getParentFile(); if(!iFileParent.exists()){ iFileParent.mkdirs(); } // 转存文件 file.transferTo(new File(filePath)); result = true; } } } return result; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。