方式一:HttpClient
public static String uploadFile(String url, Map<String, FileWrapper> fileParam, Map<String,String> otherParam){
long start = System.currentTimeMillis();
log.info("uploadFile url: {}.",url);
HttpClient client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.setProtocolVersion(HttpVersion.HTTP_1_1);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(CONN_TIMEOUT)
.setSocketTimeout(READ_TIMEOUT)
.build();
post.setConfig(requestConfig);
try {
ContentType contentType = ContentType.create("multipart/form-data", StandardCharsets.UTF_8);
MultipartEntityBuilder builder = MultipartEntityBuilder.create()
.setMode(HttpMultipartMode.RFC6532)
.setCharset(StandardCharsets.UTF_8)
.setContentType(contentType);
for (Map.Entry<String, FileWrapper> fileWrapperEntry : fileParam.entrySet()) {
String k = fileWrapperEntry.getKey();
FileWrapper v = fileWrapperEntry.getValue();
log.info("fileName: {}, fileMd5: {}",k, MD5Util.md5(FileUtils.readFileToByteArray(v.getFile())));
builder.addPart(k,new FileBody(v.getFile(),contentType, v.getFileName()));
}
if (MapUtils.isNotEmpty(otherParam)){
otherParam.forEach((k,v) -> builder.addTextBody(k,v,contentType));
}
post.setEntity(builder.build());
HttpResponse response = client.execute(post);
return EntityUtils.toString(response.getEntity(),StandardCharsets.UTF_8);
} catch (Exception e) {
log.error("uploadFile fail. url: {}",url,e);
throw new RuntimeException("uploadFile exception ", e);
}finally {
log.info("uploadFile cost {}ms",System.currentTimeMillis()-start );
}
}
public static class FileWrapper{
private File file;
private String fileName;
private String contentType;
public FileWrapper() {
}
public FileWrapper(File file, String fileName, String contentType) {
this.file = file;
this.fileName = fileName;
this.contentType = contentType;
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getContentType() {
return contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
}
方式二:RestTemplate
public String uploadFile(byte[] fileData, String fileName, LocalDateTime time) {
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("multipart/form-data");
headers.setContentType(type);
headers.setContentLength(fileData.length);
headers.setContentDispositionFormData("media", fileName);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHH");
String format = time.format(formatter);
String date = format.substring(0, 8);
String hourPart = format.substring(8, 10);
MultiValueMap<String, Object> parts = new LinkedMultiValueMap<>();
ByteArrayResource fileAsResource = new ByteArrayResource(fileData){
@Override
public String getFilename() {
return fileName;
}
@Override
public long contentLength() {
return fileData.length;
}
};
parts.add("file", fileAsResource);
parts.add("fileName", fileName);
parts.add("date", date);
parts.add("hour", hourPart);
parts.add("fileType", config.getFileType());
parts.add("businessType", config.getBusinessType());
HttpEntity<MultiValueMap<String, Object>> formEntity = new HttpEntity<>(parts, headers);
ResponseEntity<String> responseEntity = restTemplate.postForEntity(config.getUrl() + "/uploadFile", formEntity, String.class);
JSONObject response= JSONObject.parseObject(responseEntity.getBody());
if (response!= null && Integer.parseInt(response.get("code").toString()) == 0) {
return (String) response.get("path");
} else {
log.error("response is null and file name is {}", fileName);
return "";
}
}