当前位置: 首页 > article >正文

Http文件上传

方式一: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);

       //发送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 "";
       }

   }

http://www.kler.cn/a/410497.html

相关文章:

  • STM32F103C8T6实时时钟RTC
  • 《用Python画蔡徐坤:艺术与编程的结合》
  • Neural Magic 发布 LLM Compressor:提升大模型推理效率的新工具
  • Debian/Ubuntu 、Fedora 、Arch Linux, 在Linux上,对文本文件进行多线程压缩 xz、pxz、zstd、7z、lrzip
  • ODBC连接PostgreSQL数据库后,网卡DOWN后,客户端进程阻塞问题解决方法
  • Spring 框架七大模块(Java EE 学习笔记03)
  • 【数据结构与算法】合并链表、链表分割、链表回文结构
  • hhdb数据库介绍(10-6)
  • 【每天学点AI】实战图像增强技术在人工智能图像处理中的应用
  • 从尾到头打印链表 剑指offer
  • 嵌入式系统与单片机工作原理详解
  • gitee仓库的推送教程
  • 大数据新视界 -- Hive 数据桶原理:均匀分布数据的智慧(上)(9/ 30)
  • Zustand:一个轻量级的React状态管理库
  • Predicting Goal-directed Attention Control Using Inverse-Reinforcement Learning
  • 安装 Docker(使用国内源)
  • 修改bag的frame_id的工具srv_tools
  • 136.flask内置jinja2模版使用
  • 【随手笔记】GUI上位机选择
  • react和vue图片懒加载及实现原理
  • springboot项目使用maven打包,第三方jar问题
  • Java基础--输入输出
  • STM32 Keil5 attribute 关键字的用法
  • Java爬虫:数据采集的强大工具
  • Perl 简介
  • react函数式组件中的路由传参方式