使用Resteasy,如何在没有任何字符编码转换的情况下保存上传的文件?

时间:2014-07-10 15:24:03

标签: file-upload character-encoding resteasy

我尝试在服务器上使用Resteasy通过表单上传XML文件。当我收到文件时,我只是将其保存到磁盘。该文件采用UTF-8编码,但保存时将非ASCII字符转换为问号。 This stack overflow page让我相信这一行是问题所在:

//convert the uploaded file to input stream
InputStream inputStream = inputPart.getBody(InputStream.class, null);

我尝试使用预处理拦截器将编码设置为UTF-8,但这并不起作用。此外,在服务器上设置编码是错误的解决方案 - 我真的希望能够处理任何编码的文件,只需将它们保存到磁盘而不进行任何转换。有什么方法可以使用Resteasy来做到这一点吗?

以下是我用来处理上传的所有代码:

ResourcesHandler.java:

@POST
@Path("/")
@Consumes("multipart/form-data")
public void createOrReplaceResource(MultipartFormDataInput input) throws IOException {
    Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
    List<InputPart> inputParts = uploadForm.get("file");
    ResourceManager.createResource(null, inputParts);
}

ResourceManager.java:

public static void createResource(String packName, List<InputPart> inputParts) throws IOException {
    String dirname = DYNAMIC_RESOURCE_DIRECTORY;
    if (packName != null && !packName.isEmpty()) {
        dirname = dirname + "/" + packName;
    }

    //This code taken from: http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-resteasy/
    String fileName = "";
    for (InputPart inputPart : inputParts) {
        MultivaluedMap<String, String> header = inputPart.getHeaders();
        fileName = getFileName(header);

        //convert the uploaded file to inputstream
        InputStream inputStream = inputPart.getBody(InputStream.class, null);

        byte[] bytes = IOUtils.toByteArray(inputStream);

        //construct upload file path
        fileName = dirname + "/" + fileName;

        writeFile(bytes, fileName);
    }
}

//This code taken from: http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-resteasy/
//get uploaded filename, is there a easy way in RESTEasy?
private static String getFileName(MultivaluedMap<String, String> header) {

    String[] contentDisposition = header.getFirst("Content-Disposition").split(";");

    for (String filename : contentDisposition) {
        if ((filename.trim().startsWith("filename"))) {

            String[] name = filename.split("=");

            String finalFileName = name[1].trim().replaceAll("\"", "");
            return finalFileName;
        }
    }
    return null;
}

//This method taken from: http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-resteasy/
//Save to a file.
private static void writeFile(byte[] content, String filename) throws IOException {

    File file = new File(filename);

    if (!file.exists()) {
        file.createNewFile();
    }

    FileOutputStream fop = new FileOutputStream(file);

    fop.write(content);
    fop.flush();
    fop.close();

}

这是Apache commons-io IOUtils,它将InputStream转换为字节数组。

0 个答案:

没有答案