使用RESTEasy使用的文件名(Žluťoučkýkůň.txt)中的捷克字符UTF-8发送文件。但在java中我总是成为US-ASCII文件名(当然是错误的)
用于发送文件的HTML:
------WebKitFormBoundaryAyBqNu6jIFHAB660
Content-Disposition: form-data; name="file"; filename="Žluťoučký kůň.txt"
Content-Type: text/plain
真的是发送:
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain)
throws IOException, ServletException {
servletRequest.setCharacterEncoding("UTF-8");
@Override
public void filter(ContainerRequestContext requestContext) throws IOException {
requestContext.setProperty(InputPart.DEFAULT_CONTENT_TYPE_PROPERTY, "*/*; charset=UTF-8");
requestContext.setProperty(InputPart.DEFAULT_CHARSET_PROPERTY, "UTF-8");
用于获取UTF-8编码的已用过滤器:
public List<CaseFile> uploadFile(MultipartFormDataInput input, long caseId) {
MultipartFormDataOutput mdo = new MultipartFormDataOutput();
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
for (List<InputPart> inputParts : uploadForm.values()) {
for (InputPart inputPart : inputParts) {
try {
// Retrieve headers, read the Content-Disposition header to obtain the original name of the file
MultivaluedMap<String, String> headers = inputPart.getHeaders(); //here are all headers in US-ASCII
读取多部分的Java代码:
File file = new File(filePath);
Uri uri = Uri.fromFile(file);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/*");
share.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(share,
"به اشتراک گذاشتن فایل"));
和标题包含:
形式数据; NAME = “文件”; filename =“?? lu ?? ou ?? k ?? k ????。txt”
答案 0 :(得分:1)
我使用野生蝇9和resteasy。上面的代码导致我的类强制转换异常。下面的代码解决了我的问题:
Field field = inputPart.getClass().getDeclaredField("bodyPart");
field.setAccessible(true);
Object bodyPart = field.get(inputPart);
Method methodBodyPart = bodyPart.getClass().getMethod("getHeader", new Class[]{});
Iterable iterable = (Iterable)methodBodyPart.invoke(bodyPart, new Class[]{});
Object[] content = IteratorUtils.toArray(iterable.iterator());
Method methodContent = content[0].getClass().getMethod("getRaw", new Class[]{});
String[] contentDisposition = methodContent.invoke(content[0], new Class[]{}).toString().split(";");
for (String filename : contentDisposition) {
if ((filename.trim().startsWith("filename"))) {
String[] name = filename.split("=");
String finalFileName = name[1].trim().replaceAll("\"", "");
return finalFileName;
}
}