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();
}
}
}

 

 

 

 

 

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM