通过POSTMAN上传的.txt文件损坏(附加了Content-Disposition,Content-type)JAX-RS

时间:2018-12-20 12:37:56

标签: java rest file-upload jax-rs postman

问候社区!我目前正在使用RESTful web service库在Java中开发一个JAX-rs。我想做的是使客户能够通过该服务上传文件。我成功使用以下代码

实现了这一点
@Consumes({"application/json"})
@Produces({"application/json"})
@Path("uploadfileservice")
public interface UploadFileService {

   @Path("/fileupload")
   @POST
   @Consumes(MediaType.MULTIPART_FORM_DATA)
   Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream)
}

实施班

@Service
public class UploadFileServiceImpl implements UploadFileService {

@Override
public Response uploadFile(InputStream uploadedInputStream){
String fileToWrite = "//path/file.txt" //assuming a upload a txt file
writeToFile(uploadedInputStream, fileToWrite); //write the file
}

private void writeToFile(InputStream uploadedInputStream,
    String uploadedFileLocation) {

    try {
        OutputStream out = new FileOutputStream(new File(
                uploadedFileLocation));
        int read = 0;
        byte[] bytes = new byte[1024];

        out = new FileOutputStream(new File(uploadedFileLocation));
        while ((read = uploadedInputStream.read(bytes)) != -1) {
            out.write(bytes, 0, read);
        }
        out.flush();
        out.close();
    } catch (IOException e) {

        e.printStackTrace();
    }

 }
}

我使用POSTMAN作为客户端来测试我的Web服务,并且遇到以下问题:当我上传.txt文件时,该文件会附加文件的其他一些详细信息< / strong>

示例:

文件已发送

file sent

邮递员请求

postman request

文件存储在我的文件系统中

file stored

知道为什么会这样吗?也许我的请求的Headers部分中缺少某些内容?还是可能是由于我在自己的Web服务端点中消费的MediaType引起了任何问题?

在此先感谢您的帮助:)

PS

如果我上传.pdf文件,则不会导致文件损坏,并且.pdf文件通常存储在我的文件系统中

2 个答案:

答案 0 :(得分:0)

您的方法签名应为

Response uploadFile(@FormDataParam("file") FormDataBodyPart uploadedFile)

您可以将文件的内容获取为

InputStream uploadedInputStream = uploadedFile.getValueAs(InputStream.class)

希望这会有所帮助。

答案 1 :(得分:0)

最后,我使用Attachment的{​​{1}}类找到了解决问题的方法:

org.apache.cxf