【发布时间】:2015-02-03 17:43:47
【问题描述】:
我正在尝试将带有 HTML5 文件 API 的文件上传到 Java RESTful WebService。当我尝试上传 gif 图像时,服务正在接收 InputStream,我可以将该流写入服务器文件系统。不幸的是,由于创建的图像(689 字节)大于源文件(512 字节),因此出现了问题。这是我已经拥有的:
JavaScript:
var doc = document.documentElement;
doc.ondrop = function (event) {
event.preventDefault && event.preventDefault();
// now do something with:
var files = event.dataTransfer.files;
var formData = new FormData();
for (var i = 0; i < files.length; i++) {
formData.append('file', files[i]);
}
// now post a new XHR request
var xhr = new XMLHttpRequest();
xhr.open('POST', 'rs/media/upload', true);
xhr.onload = function () {
if (xhr.status === 200) {
console.log('all done: ' + xhr.status);
} else {
console.log('Something went terribly wrong...');
}
};
xhr.send(formData);
return false;
};
Java RESTful 服务:
@POST
@Path("upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@FormDataParam("file") InputStream uploadedInputStream) throws IOException
{
if (uploadedInputStream == null) {
return Response.status(Response.Status.PRECONDITION_FAILED).build();
}
writeToFile(uploadedInputStream, MEDIA_BASE_PATH + "/test.gif");
return Response.status(Response.Status.OK).build();
}
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();
}
}
有人可以告诉我这里有什么问题吗? WebService 还很初级,所以请不要怀疑我使用的是绝对目标路径。
谢谢, 格里
【问题讨论】:
标签: java javascript rest file-upload jax-rs