需要的包
<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; }
public static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private static JSONObject covertEntityToJSON(HttpEntity entity) throws Exception {
if (entity != null) {
String res = EntityUtils.toString(entity, "UTF-8");
JSONObject jsonObject = JSONObject.parseObject(res);
return jsonObject;
} else {
return null;
}
}
问题:如果传输过程中,文件名称中文乱码,可以将文件名称编码,传递过去,然后接收端解码
String name = java.net.URLEncoder.encode(name,"UTF-8");
String name = java.net.URLDecoder.decode(filename,"UTF-8");
浙公网安备 33010602011771号