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 "";
       }

   }
相关推荐
柯3491 小时前
GC垃圾回收
java·jvm·垃圾回收
redemption_21 小时前
SpringMVC-03-HelloSpring
java
平头哥在等你2 小时前
C语言简答题答案
java·c语言·jvm
LKID体2 小时前
【python图解】数据结构之字典和集合
java·服务器·前端
HUT_Tyne2652 小时前
力扣--LCR 154.复杂链表的复制
java·leetcode·链表
黄昏_2 小时前
在Springboot项目中实现将文件上传至阿里云 OSS
java·spring boot·后端·阿里云
写bug写bug2 小时前
用Java Executors创建线程池的9种方法
java·后端
期待未来的男孩3 小时前
安全加固方案
java·网络·安全
惜.己3 小时前
Jmeter中的配置原件
java·前端·数据库
zhuzhihongNO13 小时前
JVM(JAVA虚拟机)内存溢出导致内存不足,Java运行时环境无法继续
java·开发语言·jvm·内存溢出·jvm内存溢出