龙太子1314

multipart/form-data上传文件,文件名乱码问题

问题描述:

multipart/form-data上传文件,文件名乱码问题

定位:

定位在发送请求时,已经乱码:

Content-Disposition: "form-data; name="file"; filename="??test.txt"
Content-Type: application/octet-stream
Content-Transfer-Encoding: binary

解决方法:

MultipartEntity 创建时,添加参数:

MultipartEntityBuilder reqEntity = MultipartEntityBuilder.create();
reqEntity.setCharset(Charset.forName("UTF-8"));
reqEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
 
 
示例代码如下:
package com.company;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import java.util.Base64;
import org.json.JSONObject;
import java.nio.charset.Charset ;
import java.io.*;

public class test2 {

public static void doFormDataPost(String path, String sURL) throws IOException {

File file = new File(path);
String file_name = file.getName();
System.out.println(file_name);
HttpClient context = new DefaultHttpClient();
HttpPost post = new HttpPost(sURL);
//传递文件参数以及文本参数
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(Charset.forName("UTF-8"));//设置编码,解决中文乱码问题
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.addBinaryBody("files", file);//添加文件
builder.addTextBody("loginUser", "11");//添加文本类型参数
builder.addTextBody("fileType", "111"); //添加文本类型参数
builder.addTextBody("oaFlowId", "1111"); //添加文本类型参数
//将文件名称-bash64编码
Base64.Encoder encoder = Base64.getEncoder();
byte[] textByte = file_name.getBytes("UTF-8");
String encodedText = encoder.encodeToString(textByte);
builder.addTextBody("fileName", encodedText); //添加文本类型参数

//发送post请求
post.setEntity(builder.build());
HttpResponse response = context.execute(post);
HttpEntity responseEntity = response.getEntity();
String resEntity= EntityUtils.toString(responseEntity, "UTF-8");
JSONObject jsonObj = new JSONObject(resEntity);
String ret_msg = (String) jsonObj.get("message");
Integer ret_code = (Integer) jsonObj.get("return_code");
System.out.println(jsonObj);

}

public static void main(String[] args) {
try {
String strpath = "D:/风管系统测试文件.txt";
doFormDataPost(strpath ,"http://127.0.0.1/raycom/api/knowledge/upload/");
} catch (IOException e) {
e.printStackTrace();
}
}
}

 

 

 

 

 

 

 

posted on 2021-07-21 13:53  while_true_work_hard  阅读(2402)  评论(0编辑  收藏  举报

导航