Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 在MultipartEntityBuilder中编码文件名_Java_Utf 8_Multipartentity - Fatal编程技术网

Java 在MultipartEntityBuilder中编码文件名

Java 在MultipartEntityBuilder中编码文件名,java,utf-8,multipartentity,Java,Utf 8,Multipartentity,我正在尝试使用HttpPost和MultipartEntityBuilder的文件上传API。下面是我使用的代码 MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(MIME.UTF8_CHARSET); builder.addBinaryBody(<fileFieldName>, <byteArray>, ContentType.TEXT_PLAIN,

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

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setCharset(MIME.UTF8_CHARSET);
builder.addBinaryBody(<fileFieldName>, <byteArray>, ContentType.TEXT_PLAIN, <fileName>);
文件已正确上载。但当文件名包含非ASCII字符时,它会以名称???.jpg上传。尝试了这里给出的解决方案。但这并没有解决我的问题。请帮忙

你能举个例子吗。 考虑使用不同的编码 字符集

描述

US-ASCII七位ASCII,也称ISO646-US,也称为Unicode字符集的基本拉丁块 ISO-8859-1 ISO拉丁字母表1,又称ISO拉丁字母表1 UTF-8八位UCS转换格式 UTF-16BE 16位UCS转换格式,大端字节顺序 UTF-16LE 16位UCS转换格式,小端字节顺序 UTF-16 16位UCS转换格式,由可选字节顺序标记标识的字节顺序

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

只需将值替换为您的值…

以防您不想处理物理文件,并且想法是发送一个请求,已经有byte[]数据,例如作为一个多部分文件或从数据库读取,您也可以完全忘记生成器中包含的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)));
然后在另一侧,如弹簧座:

@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.setModeHttpMultipartMode.RFC6532;在我的情况下发挥了魔力。还要检查服务器是否接受UTF-8编码的文件名。在我的例子中,它是ApacheSlingPostServlet,我必须更新默认的服务器编码

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

我会考虑如何使用格式化工具。您可以将其包含在我使用的代码块中,实现组:'org.apache.httpcomponents',名称:'httpclient android',版本:'4.3.5.1'implementation'org.apache.httpcomponents:httpime:4.3'{exclude module:httpclient}用于使用MultipartEntityBuilder类实体