I am newbie in Java EE and I'd like a user to upload a file XML by its file system. My app is using API REST.The file to upload is successfully uploaded to the server (in localhost) but I notice some metadata information is a part of this new file so it gets stuck there!
Example: To upload a file "web.xml", here is what is added to the header and end of the new file (server side)
Header:
------WebKitFormBoundarybi7qp5AIFEXbebt7
Content-Disposition: form-data; name="datafile"; filename="web.xml"
Content-Type: text/xml
End of new file
------WebKitFormBoundarybi7qp5AIFEXbebt7--
See below HTML client file and server side code
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>
We've got this above 'Client.HTML' via a simple GET method from server. When submitting the form, the POST method below is called
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();
}
}
Any help or tricks to solve it, please?