繁体   English   中英

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

[英]Uploaded .txt file through POSTMAN gets corrupted (appended with Content-Disposition, Content-type) JAX-RS

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

@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服务,并且POSTMAN以下问题: 当我上传.txt文件时,该文件会附加文件的其他一些详细信息

例:

文件已发送

文件已发送

邮递员要求

邮递员要求

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

文件存储

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

在此先感谢您的帮助:)

PS

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

您的方法签名应为

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

您可以获取文件的内容为

InputStream uploadedInputStream = uploadedFile.getValueAs(InputStream.class)

希望这可以帮助。

最后,我使用org.apache.cxfAttachment类找到了解决此问题的方法:

@Consumes({"application/json"})
@Produces({"application/json"})
@Path("uploadfileservice")
public interface UploadFileService {

@Path("/fileupload")
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
Response uploadFile(@Multipart("file") Attachment attr)
}



@Service
public class UploadFileServiceImpl implements UploadFileService {

@Override
public Response uploadFile(Attachment attr){
String pathToUpload= "//path//.txt"
try{
  attr.transferTo(new File(pathToUpload)); //will copy the uploaded file in 
  //this destination
}
catch(Exception e){

}

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM