```java
package com.utils;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Base64;
public class UploadFile {
private static final String boundary = "----WebKitFormBoundary0jkH3KeWg3pxZxJ5"; // 分隔不同字段的边界字符串
/**
* http上传文件抓方法
* @param base64Code 文件base64编码
* @return 上传成功的json字符串
* @throws Exception Exception
*/
public static String uploadFn(String base64Code,String port) throws Exception {
// String path ="D:\\wx\\WeChat Files\\wxid_ma3xknryhe2i22\\FileStorage\\File\\2024-05\\11.txt";
// try (BufferedReader br = new BufferedReader(new FileReader(path))) {
// String line;
// while ((line = br.readLine()) != null) {
// base64Code = line;
// }
// } catch (IOException e) {
// e.printStackTrace();
// }
// 初始化URL对象:
URL url = new URL(port);
// 打开连接并设置方法:
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
// 设置其他请求头:
//设置Content-Type以指示你正在发送多部分形式的数据,通常用于文件上传
httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
// 开启输出流
httpURLConnection.setDoOutput(true);
DataOutputStream outputStream = new DataOutputStream(httpURLConnection.getOutputStream());
// 添加参数:
String fieldName = System.currentTimeMillis()+".png";
setFileByBase64(outputStream, base64Code, fieldName);
setParam(outputStream, "filename", fieldName); // 添加文本参数
setParam(outputStream, "action", "uploadfile"); // 添加文本参数
setParam(outputStream, "calltoken", "3979189c96de598a7c2e10433bb1885a"); // 添加文本参数
setParam(outputStream, "jsontype", ""); // 添加文本参数
setParam(outputStream, "userid", "23af16b1-1ca3-4054-bc20-71d425eb48da"); // 添加文本参数
setParam(outputStream, "customercode", "2020"); // 添加文本参数
// 结束多部分数据:
outputStream.writeBytes("\r\n--" + boundary + "--\r\n");
// 关闭流
outputStream.flush();
outputStream.close();
// 读取响应
int responseCode = httpURLConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
// 处理成功的响应
BufferedReader in = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
String inputLine;
StringBuilder content = new StringBuilder();
while ((inputLine = in.readLine()) != null) {
content.append(inputLine);
}
in.close();
return content.toString();
} else {
return "{}";
// 处理错误情况
}
}
/**
* post 字符串参数
*
* @param outputStream 请求流
* @param key 字段名
* @param value 字段值
* @throws Exception ioException
*/
public static void setParam(DataOutputStream outputStream, String key, String value) throws Exception {
outputStream.writeBytes("\r\n--" + boundary + "\r\n");
outputStream.writeBytes("Content-Disposition: form-data; name=\"" + key + "\"\r\n\r\n");
outputStream.writeBytes(value);
}
/**
* post文件参数
*
* @param outputStream 请求流
* @param path 文件物理地址
* @throws Exception ioException
*/
public void setFile(DataOutputStream outputStream, String path) throws Exception {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
byte[] fileBytes = new byte[(int) file.length()];
fis.read(fileBytes);
outputStream.writeBytes("\r\n--" + boundary + "\r\n");
outputStream.writeBytes("Content-Disposition: form-data; name=\"upfile\"; filename=\"" + file.getName() + "\"\r\n");
outputStream.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
outputStream.write(fileBytes);
}
/**
* post文件参数
*
* @param outputStream 请求流
* @param base64 文件base64编码
* @param fieldName 文件名
* @throws Exception ioException
*/
public static void setFileByBase64(DataOutputStream outputStream, String base64, String fieldName) throws Exception {
// base64解码转二进制
byte[] decodedBytes = Base64.getDecoder().decode(base64);
outputStream.writeBytes("\r\n--" + boundary + "\r\n");
outputStream.writeBytes("Content-Disposition: form-data; name=\"upfile\"; filename=\"" + fieldName + "\"\r\n");
outputStream.writeBytes("Content-Type: application/octet-stream\r\n\r\n");
outputStream.write(decodedBytes);
}
}
java实现HTTP文件传输
于 2024-05-21 16:21:35 首次发布