public Map<String, String> webUpload(Map<String, Object> param, MultipartFile file) throws Exception {
String request_url = "xXXXXXXXXXXXXXXXXXXXXXXx";
//上传文件
// 换行符
final String newLine = "\r\n";
final String boundaryPrefix = "--";
// 定义数据分隔线
String BOUNDARY = "========7d4a6d158c9";
// 服务器的域名
URL url = new URL(request_url );
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
// 设置为POST情
conn.setRequestMethod("POST");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
//设置请求头参数
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("Charset", "UTF-8");
conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + BOUNDARY);
OutputStream out = new DataOutputStream(conn.getOutputStream());
//参数用户名user_name
StringBuilder sb2 = new StringBuilder();
sb2.append(boundaryPrefix);
sb2.append(BOUNDARY);
sb2.append(newLine);
sb2.append("Content-Disposition: form-data;name=\"user_name\"");
sb2.append(newLine);
sb2.append(newLine);
sb2.append(param.get("user_name"));
sb2.append(newLine);
out.write(sb2.toString().getBytes());
// 上传文件
StringBuilder sb = new StringBuilder();
sb.append(boundaryPrefix);
sb.append(BOUNDARY);
sb.append(newLine);
// 文件参数
sb.append("Content-Disposition: form-data;name=\"print_file\";filename=\"" + param.get("fileName").toString()+ "\"" + newLine);
sb.append("Content-Type: ").append(file.getContentType());
// 参数头设置完以后需要两个换行,然后才是参数内容
sb.append(newLine);
sb.append(newLine);
// 将参数头的数据写入到输出流中
out.write(sb.toString().getBytes());
// 数据输入流,用于读取文件数据
DataInputStream in = new DataInputStream(file.getInputStream());
byte[] bufferOut = new byte[1024];
int bytes = 0;
// 将文件数据写入到输出流中
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
/*
* 坑坑坑,不要再末尾添加空白,否则会被计入文件流,影响文件编码,office03、pdf因为会自动补位到1024的整数倍,因此无影响
*/
// out.write(newLine.getBytes());
in.close();
// 定义最后数据分隔线,即--加上BOUNDARY再加上--。
byte[] end_data = (newLine + boundaryPrefix + BOUNDARY + boundaryPrefix + newLine)
.getBytes();
// 写上结尾标识
out.write(end_data);
out.flush();
out.close();
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
// 定义BufferedReader输入流来读取URL的响应
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = null;
String result="";
while ((line = reader.readLine()) != null) {
result += line; //这里读取的是上边url对应的上传文件接口的返回值
}
//转xml为map
Map<String, String> map = CommonUtils.xmlToMap(result);
reader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
conn.disconnect();
return map;
}
java后端发送请求中附带文件
最新推荐文章于 2024-08-05 09:09:27 发布