場景是自己的web端需要上傳文件到別人的接口上,
我自己的頁面上傳文件到后台就不需要說什么了,關鍵是要把文件直接上傳到接口,當然還有其他參數。
Controller
@RequestMapping(value="/uploadExcel", produces = "application/json;charset=UTF-8") public @ResponseBody String uploadExcel(@RequestParam Map<String, String> data, @RequestParam("file") MultipartFile file) throws Exception { return service.uploadExcel(data, file); }
service
public String uploadExcel(Map<String, String> data, MultipartFile file) throws Exception { return doPostFileRequest("/item/direction/coupon/uploadCouponExcel", data, file.getInputStream(), file.getOriginalFilename()); }
util
protected String doPostFileRequest(String url, Map<String, String> param, InputStream fis, String fileName) throws Exception {try { Connection conn = Jsoup.connect(user.getJdDomain() + url); if (param != null) { conn.data(param); } conn.data("file", fileName, fis); Connection.Response response = conn.timeout(DEFAULT_TIME_OUT).ignoreContentType(true).maxBodySize(0).followRedirects(true).method(Connection.Method.POST).execute(); return response.body(); } catch (UncheckedIOException var7) { throw new IOException(var7); } }
上面是上傳,就是data方法
下載文件代碼,請求別人的接口獲取文件流,然后返回前台下載。
@RequestMapping(value="/exportSyncResult", produces = "application/json;charset=UTF-8") public void exportSyncResult(@RequestParam Map<String, String> data, HttpServletResponse response) throws Exception { Connection.Response response1 = service.exportSyncResult(data); byte[] bytes = response1.bodyAsBytes(); String s = response1.contentType(); String header1 = response1.header("Content-Disposition"); response.addHeader("Content-Disposition", header1); response.setContentType(s); response.getOutputStream().write(bytes); }
@Override public Connection.Response exportSyncResult(Map<String, String> data) throws Exception { return getResponseIn("/item/direction/coupon/exportSyncResult", data); }
public Connection.Response getResponseIn(String url, Map<String, String> param) throws Exception { getParam(param); User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user"); try { Connection conn = Jsoup.connect(user.getJdDomain() + url); if (param != null) { conn.data(param); } Connection.Response response = conn.timeout(DEFAULT_TIME_OUT).ignoreContentType(true).maxBodySize(0).followRedirects(true).method(Connection.Method.GET).execute(); return response; } catch (UncheckedIOException var7) { throw new IOException(var7); } }