需要的包
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.3.1</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.8</version>
</dependency>
接收前端上传的文件
public String uploadProductAttachment(MultipartFile file) throws MicroException { if(file == null || file.isEmpty()){ throw new MicroException(HttpStatus.BAD_REQUEST.value(), Commons.DATA_IS_NULL); } File toFile = null; InputStream ins = null; try { ins = file.getInputStream(); toFile = new File(file.getOriginalFilename()); inputStreamToFile(ins, toFile); JSONObject result = RestUtil.postUploadFile(baseConfig.getForwardRootUrl() + "/uploadProductAttachment", toFile); if(result.getIntValue("code") == OK){ JSONObject resultData = result.getJSONObject("data"); if(resultData != null){ if(resultData.getBoolean("success")){ JSONArray data = resultData.getJSONArray("data"); if(data != null && data.size() > 0){ JSONObject a = data.getJSONObject(0); return a.getString("id"); } } } } } catch (Exception e) { e.printStackTrace(); LOG.error(e.getMessage()); throw new MicroException(HttpStatus.BAD_REQUEST.value(), Commons.ERROR); }finally { if(ins != null){ try { ins.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }
public static JSONObject postUploadFile(String url, File file){ CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; try { httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); InputStreamBody bin = new InputStreamBody(new FileInputStream(file), file.getName()); HttpEntity reqEntity = MultipartEntityBuilder.create() .setCharset(Charset.forName("UTF-8")) // 相当于<input type="file" name="file"/> .addPart("file", bin) .build(); httpPost.setEntity(reqEntity); // 发起请求 并返回请求的响应 response = httpClient.execute(httpPost); return covertEntityToJSON(response.getEntity()); }catch (Exception e){ e.printStackTrace(); }finally { if(response != null){ try { response.close(); } catch (IOException e) { e.printStackTrace(); } } if(httpClient != null){ try { httpClient.close(); } catch (IOException e) { e.printStackTrace(); } } } return null; }