Java实现以form-data形式文件上传到服务器

Java实现以form-data形式文件上传到服务器

package com.joolun.cloud.mall.common.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Map;

@Slf4j
public class HttpFileUtil {
		/**
		 * 以post方式调用第三方接口,以form-data 形式  发送 MultipartFile 文件数据
		 * @param url  post请求url
		 * @param fileParamName 文件参数名称
		 * @param multipartFile  文件
		 * @param paramMap  文件之外其他参数
		 */
		public static String doPostFormData(String url, String fileParamName, MultipartFile multipartFile, Map<String, String> paramMap) {
			log.info("文件参数名称"+fileParamName);
			// 创建Http实例
			CloseableHttpClient httpClient = HttpClients.createDefault();
			// 创建HttpPost实例
			HttpPost httpPost = new HttpPost(url);
			// 请求参数配置
			RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(60000).setConnectTimeout(60000)
					.setConnectionRequestTimeout(10000).build();
			httpPost.setConfig(requestConfig);
			//请求头设置
			try {
				MultipartEntityBuilder builder = MultipartEntityBuilder.create();
				builder.setCharset(StandardCharsets.UTF_8);
				builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
				String fileName = multipartFile.getOriginalFilename();
				// 文件流
				builder.addBinaryBody(fileParamName, multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, fileName);
				//表单中其他参数,如果没有其他参数可以注释该部分
				for(Map.Entry<String, String> entry: paramMap.entrySet()) {
					builder.addPart(entry.getKey(),new StringBody(entry.getValue(), ContentType.create("text/plain", Consts.UTF_8)));
				}
				log.info("builder"+builder);
				HttpEntity entity = builder.build();
				httpPost.setEntity(entity);

				log.info("请求url:"+url);
				log.info("请求参数:"+paramMap.toString());
				// 执行提交
				HttpResponse response = httpClient.execute(httpPost);
				if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
					// 返回
					String res = EntityUtils.toString(response.getEntity(), StandardCharsets.UTF_8);
					log.info("请求返回数据"+res);
					JSONObject resJson= JSON.parseObject(res);
					if ("200".equals(resJson.get("code").toString())) {
						JSONObject data = (JSONObject) resJson.get("data");
						return data.get("fileUrl").toString();
					}
					return res;
				}
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				if (httpClient != null) {
					try {
						httpClient.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
			return null;
		}
	}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
Java实现文件上传的常用方式是使用HTTP协议的`multipart/form-data`格式,具体实现步骤如下: 1. 创建一个`HttpURLConnection`连接对象,设置请求方法为POST,并设置连接超时时间和读取超时时间。 2. 设置请求头信息,包括`Content-Type`、`User-Agent`、`Accept-Language`等,其中`Content-Type`设置为`multipart/form-data`。 3. 创建输出流,并将需要上传的文件写入到输出流中。在写入文件之前需要设置一个分隔符,用于分隔不同字段的内容。 4. 在输出流的末尾写入分隔符,表示文件上传结束。 5. 发送HTTP请求,并读取服务器返回的响应结果。 下面是一个Java实现文件上传的示例代码: ```java public static void uploadFile(String url, File file) throws IOException { String boundary = "---------------------------" + System.currentTimeMillis(); //设置分隔符 HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection(); //创建连接对象 conn.setRequestMethod("POST"); //设置请求方法为POST conn.setConnectTimeout(5000); //设置连接超时时间 conn.setReadTimeout(30000); //设置读取超时时间 conn.setDoOutput(true); //允许输出 conn.setDoInput(true); //允许输入 conn.setUseCaches(false); //不使用缓存 conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); //设置请求头信息 conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"); conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8"); OutputStream out = new DataOutputStream(conn.getOutputStream()); //创建输出流 FileInputStream fileInputStream = new FileInputStream(file); //创建文件输入流 byte[] buffer = new byte[1024]; int len = 0; out.write(("--" + boundary + "\r\n").getBytes()); //写入分隔符 out.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n").getBytes()); out.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes()); while ((len = fileInputStream.read(buffer)) != -1) { out.write(buffer, 0, len); //写入文件数据 } out.write(("\r\n--" + boundary + "--\r\n").getBytes()); //写入分隔符 out.flush(); //清空缓存 fileInputStream.close(); //关闭文件输入流 out.close(); //关闭输出流 int responseCode = conn.getResponseCode(); //获取响应码 if (responseCode == 200) { InputStream inputStream = conn.getInputStream(); //获取响应输入流 BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream)); //创建读取响应结果的缓冲流 String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); //输出响应结果 } bufferedReader.close(); //关闭缓冲流 inputStream.close(); //关闭输入流 } else { System.out.println("文件上传失败,响应码为:" + responseCode); } } ``` 其中,`url`为上传文件的URL,`file`为需要上传的文件。在实际使用时,需要根据实际情况更改请求头信息、分隔符和文件字段名等参数。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

XuDream

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值