Как настроить UTF-8 для загрузки файла в java? - PullRequest
0 голосов
/ 16 апреля 2020

У меня есть функция для загрузки файла ниже:

public static Map<Integer, Map<String, byte[]>> getFiles(IMultipartBody bimp) {
        List<IAttachment> parts = bimp.getAllAttachments();
        Iterator<IAttachment> it = parts.iterator();
        ByteArrayOutputStream baos = null;
        InputStream inputStream = null;
        String fileName = null;
        byte[] bytes = null;

        Map<Integer, Map<String, byte[]>> files = new HashMap<Integer, Map<String, byte[]>>();
        Map<String, String> duplicateFileMap = new HashMap<String, String>();
        int counter = 0;

        while (it.hasNext()) {
            try {
                IAttachment name = (IAttachment) it.next();
                MultivaluedMap<String, String> headers = name.getHeaders();

                if (headers.get("Content-Disposition") != null
                        && !headers.get("Content-Disposition").isEmpty()) {
                    String header = headers.get("Content-Disposition").get(0);
                    String[] dispositions = header.split(";");
                    for (String disposition : dispositions) {
                        if (disposition.indexOf("filename") != -1) {
                            String tmpStr = disposition.substring(
                                    disposition.indexOf("=") + 1,
                                    disposition.length()).replaceAll("\"",
                                    Constant.EMPTY);
                            ByteBuffer byteBuffs = StandardCharsets.UTF_8.encode(tmpStr);
                            fileName = StandardCharsets.UTF_8.decode(byteBuffs).toString();
//                          fileName = new String(tmpStr.getBytes(), Charset.forName("UTF-8"));

                        }
                    }
                }

                inputStream = name.getDataHandler().getInputStream();
                baos = new ByteArrayOutputStream();
                int reads = inputStream.read();
                while (reads != -1) {
                    baos.write(reads);
                    reads = inputStream.read();
                }
                bytes = baos.toByteArray();
                if (bytes == null || bytes.length < 1) {
                    continue;
                }

                Map<String, byte[]> file = new HashMap<String, byte[]>();
                if (fileName != null ){
                    // Fix for firefox, remove '/'
                    if (fileName.startsWith("/")){
                        fileName = fileName.substring(1);
                    }

                    // Fix for IE, remove physical address, only get file name
                    if (fileName.lastIndexOf("\\") != -1 ){
                        fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
                    }
                }

                String md5 = generateMD5CheckSum(bytes);
                if (duplicateFileMap.containsKey(md5)
                        && duplicateFileMap.get(md5).equalsIgnoreCase(fileName)){
                    continue;
                }
                counter++;
                file.put(fileName, bytes);
                duplicateFileMap.put(md5,fileName);
                files.put(Integer.valueOf(counter), file);

            } catch (IOException e) {
                e.printStackTrace();
                LOGGER.error(e.getMessage());
            } finally {
                try {
                    if (inputStream != null) {
                        inputStream.close();
                    }

                    if (baos != null) {
                        baos.close();
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                    LOGGER.error(e.getMessage());
                }
            }
        }
        return files;
    }

Но когда я отлаживаю с загрузкой файла, есть fileName: ALMS_ ขั้น ตอน ลง ทะเบียน. Pdf (это тайский язык), заголовки Attachment имеют ниже:

{Content-Disposition = [form-data; Name = "файл"; имя файла = "ALMS_à¸,ภ± ๠‰ ™ • Ä ™ ¥ на ‡ Ä ° ๠€ บà¸μภ¢ ™ .pdf"] , Content-Type = [application / pdf], Content-ID = [root. message@cxf.apache.org]}

Я думаю, что IMultipartBody не установлен UTF-8 перед загрузкой. Кто-нибудь может помочь мне решить эту проблему? Спасибо.

1 Ответ

0 голосов
/ 16 апреля 2020

Использование заголовка Content-Disposition распространяется на RFC6266

Атрибут filename должен быть закодирован в ISO-8859-1. Другие наборы символов могут поддерживаться с использованием того же атрибута имени, за которым следуют звездочка, filename* и имя файла в кодировке URL.

См. Пример раздела 5 в RF C, для имени файла "ставки в евро" (курс евро) в кодировке UTF-8:

filename*=UTF-8''%e2%82%ac%20rates

Да, это странная запись, а не опечатка: исходное имя атрибута сопровождается звездочкой, а значение начинается с кодировки (UTF-8 ), за которыми следуют две кавычки и имя файла в кодировке URL (обратите внимание, что это кодировка пути, а не кодирование параметров: пробелы заменяются на% 20, а не на +).

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...