在 MultipartEntityBuilder 中编码文件名

Encode filename in MultipartEntityBuilder

我正在尝试使用 HttpPost 和 MultipartEntityBuilder 上传文件 API。以下是我使用过的代码。

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);
builder.addBinaryBody(<fileFieldName>, <byteArray>, ContentType.TEXT_PLAIN, <fileName>);

文件已正确上传。但是当文件名包含非 ASCII 字符时,它会以名称“????.jpg”上传。尝试了此处给出的解决方案 。但这并没有解决我的问题。请协助。

  1. 你能举个例子吗
  2. 考虑使用不同的编码

字符集

描述

US-ASCII 七位 ASCII,a.k.a。 ISO646-美国,a.k.a。 Unicode 字符集的基本拉丁语块 ISO-8859-1 ISO 拉丁字母编号 1,a.k.a。 ISO-LATIN-1 UTF-8 八位 UCS 转换格式 UTF-16BE 十六位 UCS 转换格式,大端字节顺序 UTF-16LE 十六位 UCS 转换格式,小端字节顺序 UTF-16 十六位 UCS 转换格式,由可选字节顺序标记标识的字节顺序

这对我有用:

MultipartEntityBuilder b = MultipartEntityBuilder.create();
b.addPart("file", new FileBody(<FILE>, <CONTENTTYPE>, <FILENAME>)).setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
b.setCharset(StandardCharsets.UTF_8);

只需将 <> 值替换为您的...

如果您不想处理物理文件,并且想要发送一个请求,已经有 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
}

如果要更改文件名,可以使用以下代码进行更改:

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

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