Http文件上传

方式一:HttpClient

java 复制代码
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

java 复制代码
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);

       //发送post请求上传文件
       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 "";
       }

   }
相关推荐
tealcwu14 分钟前
【游戏设计原理】32 - 消费者剩余
java·开发语言·游戏
小马爱打代码24 分钟前
Spring Boot项目开发常见问题及解决方案(下)
java·spring boot·后端
潜意识起点25 分钟前
计算机专业文献检索期末论文
java·开发语言
Q_19284999061 小时前
基于Spring Boot的工商局商家管理系统
java·spring boot·后端
m0_748232641 小时前
[MySQL报错]关于发生net start mysql 服务无法启动,服务没有报告任何错误的五种解决方案。
java
小学鸡!1 小时前
idea报错:There is not enough memory to perform the requested operation.
java·intellij-idea
L.S.V.2 小时前
Java 溯本求源之基础(三十)——封装,继承与多态
java·开发语言
码农爱java2 小时前
设计模式--装饰器模式【结构型模式】
java·设计模式·面试·装饰器模式·原理·23 中设计模式
星就前端叭3 小时前
【开源】一款基于SpringBoot的智慧小区物业管理系统
java·前端·spring boot·后端·开源
带刺的坐椅3 小时前
RxSqlUtils(base R2dbc)
java·reactor·solon·r2dbc