So I am using following Rest method in my web application to upload files. When I upload Text files, they are saved properly and i can open them. But in case of any other format i.e. *.docx or *.pdf or *.jpg, the files are stored with exact size as original files but are corrupted. Following is the code:
@POST
@Consumes("multipart/form-data")
public Response readFile() throws IOException, ServletException {
Part filePart = request.getPart("c");
InputStream f = filePart.getInputStream();
String l = null;
DataInputStream ds = new DataInputStream(f);
File file = new File("c:\\temp\\" + getSubmittedFileName(filePart));
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(file));
while ((l = ds.readLine()) != null) {
bw.write(l);
}
bw.flush();
bw.close();
return Response.status(201).entity("File Created").build();
} catch (Exception e) {
e.printStackTrace();
}
return Response.status(500).build();
}
and the html page as follows:
<form action="api/fetch" method="post" enctype="multipart/form-data">
<input id="c" name="c" type="file" aria-required="true"><br/><br/>
<button type="submit">Submit</button>
</form>
I assume there must be another way to upload files rather than this. i have refereed to How to upload files to server using JSP/Servlet? but i assume it doesn't say anything about handling file extension. So, what is going wrong with my code?