我是Java EE中的新手,我希望用户可以通过文件系统上载文件XML。我的应用程序正在使用API REST。要上传的文件已成功上载到服务器(在本地主机中),但我注意到一些元数据信息是这个新文件的一部分,因此它被卡住了!使用API REST通过文件系统上传的文件
示例:要上传文件“的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();
}
}
任何帮助或窍门,请解决它?