【发布时间】:2014-12-30 10:33:02
【问题描述】:
我是 Java EE 的新手,我希望用户通过其文件系统上传文件 XML。我的应用正在使用 API REST。要上传的文件已成功上传到服务器(在 localhost 中),但我注意到一些元数据信息是这个新文件的一部分,所以它卡在那里!
示例:上传文件“web.xml”,这里是添加到新文件头和尾的内容(服务器端)
Header:
------WebKitFormBoundarybi7qp5AIFEXbebt7
Content-Disposition: form-data; name="datafile"; filename="web.xml"
Content-Type: text/xml
End of new file
------WebKitFormBoundarybi7qp5AIFEXbebt7--
参见下面的 HTML 客户端文件和服务器端代码
Client.HTML
</body>
<form action="rest/file/upload" enctype="multipart/form-data" method="post">
<p>
Entrer un fichier xml:<br>
<input type="file" name="datafile" size="40">
</p>
<div>
<input type="submit" value="Send">
</div>
</form>
</body>
我们通过服务器的简单 GET 方法在“Client.HTML”上方得到了这个。提交表单时,调用下面的POST方法
UploadService.java
@Path("/file")
public class UploadService {
@POST
@Path("/upload")
@Produces("text/html")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(@Context HttpServletRequest request) {
String uploadedFileLocation = "D:\\rest.xml";
InputStream in;
try {
in = request.getInputStream();
// save it
writeToFile(in, uploadedFileLocation);
} catch (IOException e) {
}
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
请问有什么解决方法或技巧吗?
【问题讨论】:
标签: java rest upload header jax-rs