У меня есть функция для загрузки файла ниже:
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 перед загрузкой. Кто-нибудь может помочь мне решить эту проблему? Спасибо.