我正在尝试使用HttpPost和MultipartEntityBuilder的文件上传API。以下是我使用的代码。
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);
builder.addBinaryBody(<fileFieldName>, <byteArray>, ContentType.TEXT_PLAIN, <fileName>);
文件正确上传。但是当文件名包含非ASCII字符时,会上传名称为“????。jpg”。试过这里给出的解决方案https://stackoverflow.com/a/25870301/3271472。但它没有解决我的问题。请协助。
答案 0 :(得分:3)
这对我有用:
MultipartEntityBuilder b = MultipartEntityBuilder.create();
b.addPart("file", new FileBody(<FILE>, <CONTENTTYPE>, <FILENAME>)).setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
b.setCharset(StandardCharsets.UTF_8);
只需将<>值替换为您的值...
答案 1 :(得分:0)
字符集
描述
US-ASCII七位ASCII,a.k.a。ISO646-US,a.k.a。Unicode字符集的Basic Latin块 ISO-8859-1 ISO拉丁字母第1号,a.k.a。ISO-LATIN-1 UTF-8八位UCS转换格式 UTF-16BE 16位UCS转换格式,大端字节顺序 UTF-16LE 16位UCS转换格式,little-endian字节顺序 UTF-16 16位UCS转换格式,由可选字节顺序标记
标识的字节顺序答案 2 :(得分:0)
如果您不想处理物理文件并且想法是发送已经有byte[]
数据(例如作为MultiPartFile
或从数据库读取)的请求,则可以还完全忘记了构建器中包含的fileName
参数(只需保留原样),并分别处理文件名。示例:
byte[] data = ... // assume it comes from somewhere
String fileName = "Kąśliwa_żółta_jaźń.zip";
MultipartEntityBuilder builder = MultipartEntityBuilder.create().setCharset(StandardCharsets.UTF_8);
builder.addBinaryBody("file", data, ContentType.create(file.getContentType()), fileName);
builder.addPart("name", new StringBody(fileName, ContentType.create("text/plain", StandardCharsets.UTF_8)));
然后在另一侧(例如Spring REST):
@PostMapping("/someUrl")
public ResponseEntity<Void> handle(@RequestParam("file") MultipartFile file, @RequestParam("name") String name) {
// handle it
}
答案 3 :(得分:0)
如果要更改文件名,可以使用以下代码进行更改:
class BackgroundUploader extends AsyncTask<Void, Integer, String> {
private File file;
HttpClient httpClient = new DefaultHttpClient();
private Context context;
private Exception exception;
public BackgroundUploader(String url, Long file) {
this.context = context;
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(Void... voids) {
HttpResponse httpResponse = null;
HttpEntity httpEntity = null;
String responseString = null;
file = new File(selectedFilePath);
String boundary = "*****";
try {
String fileExt = MimeTypeMap.getFileExtensionFromUrl(selectedFilePath);
Long tsLong = System.currentTimeMillis()/1000;
final String ts = tsLong.toString().trim() +"."+ fileExt;
HttpPost httpPost = new HttpPost(AllUrl.Upload_Material);
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
Log.d("checkFile", String.valueOf(file));
// Add the file to be uploaded
//multipartEntityBuilder.addPart("file", new FileBody(file));
multipartEntityBuilder.addPart("file", new FileBody(file, ContentType.MULTIPART_FORM_DATA,ts));
multipartEntityBuilder.addPart("title",new StringBody("titlep",ContentType.MULTIPART_FORM_DATA));
// Progress listener - updates task's progress
MyHttpEntity.ProgressListener progressListener =
new MyHttpEntity.ProgressListener() {
@Override
public void transferred(float progress) {
publishProgress((int) progress);
}
};
// POST
httpPost.setEntity(new MyHttpEntity(multipartEntityBuilder.build(),
progressListener));
httpResponse = httpClient.execute(httpPost);
httpEntity = httpResponse.getEntity();
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200) {
// Server response
responseString = EntityUtils.toString(httpEntity);
runOnUiThread(new Runnable() {
@Override
public void run() {
tvFileName.setText("File Upload completed.\n\n You can see the uploaded file here: \n\n" + " "+ ts);
}
});
} else {
responseString = "Error occurred! Http Status Code: "
+ statusCode;
}
} catch (UnsupportedEncodingException | ClientProtocolException e) {
e.printStackTrace();
Log.e("UPLOAD", e.getMessage());
this.exception = e;
} catch (IOException e) {
e.printStackTrace();
}
return responseString;
}
@Override
protected void onPostExecute(String result) {
// Close dialog
dialog.dismiss();
Toast.makeText(getApplicationContext(),
result, Toast.LENGTH_LONG).show();
//showFileChooser();
}
@Override
protected void onProgressUpdate(Integer... progress) {
// Update process
dialog.setProgress((int) progress[0]);
}
}
File file = new File(selectedFilePath);
Long totalSize = file.length();
new BackgroundUploader(selectedFilePath,totalSize).execute();
}
答案 4 :(得分:0)
builder.setMode(HttpMultipartMode.RFC6532);
在我看来很神奇。还要检查您的服务器是否接受UTF-8编码的文件名。就我而言,它是Apache Sling Post Servlet,我必须更新默认服务器编码。
FileBody fileBody = new FileBody(file, ContentType.create("application/pdf"), "Příliš sprostý vtip.pdf");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.RFC6532);
builder.addPart("Příliš sprostý vtip.pdf", fileBody);
builder.addPart("žabička2", new StringBody("žabička", ContentType.MULTIPART_FORM_DATA.withCharset("UTF-8")));
HttpEntity entity = builder.build();
post.setEntity(entity);
CloseableHttpClient client = HttpClients.createDefault();
HttpResponse response = client.execute(post);