【发布时间】:2019-05-20 23:42:37
【问题描述】:
向社区致敬!我目前正在使用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 作为客户端来测试我的网络服务,但我遇到了以下问题:当我上传 .txt 文件时,该文件会附加该文件的一些其他详细信息
例子:
文件发送
邮递员请求
文件存储在我的文件系统中
知道为什么会这样吗?也许我在我的请求的Headers 部分遗漏了一些东西?或者,我在 Web 服务端点中使用的 MediaType 可能会导致任何问题?
提前感谢您的帮助:)
附言
如果我上传 .pdf 文件,它不会导致损坏,并且 .pdf 文件会正常存储在我的文件系统中
【问题讨论】:
标签: java rest file-upload jax-rs postman