通过 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)
}

实施class

@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 作为客户端来测试我的网络服务,但我遇到了以下问题:当我上传 .txt 文件时,该文件会附加一些其他详细信息文件

示例:

文件已发送

邮递员请求

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

知道为什么会这样吗?也许我在请求的 Headers 部分遗漏了什么?或者可能是因为 MediaType 我在我的 Web 服务端点中使用引起的任何问题?

提前感谢您的帮助:)

PS

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

你的方法签名应该是

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

你可以得到文件的内容为

InputStream uploadedInputStream = uploadedFile.getValueAs(InputStream.class)

希望对您有所帮助。

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

@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){

}

}