Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dropwizard file upload

Tags:

I have to upload a file from my site yet cnt seem to get it working with drop wizard.

Here is the form from my site.

   <form enctype="multipart/form-data" method="POST" action="UploadFile">      <input type="file" id="fileUpload" name="file"/>      <input type="hidden" id="fileName" name="fileName"/>      <input type="submit" value="Upload"/>    </form> 

How would I go about on the backend to receive the file?

The solution was

    @POST     @Consumes(MediaType.MULTIPART_FORM_DATA)     public Response uploadFile(         @FormDataParam("file") final InputStream fileInputStream,         @FormDataParam("file") final FormDataContentDisposition contentDispositionHeader) {       String filePath = uploadLocation + newFileName;     saveFile(fileInputStream, filePath);     String output = "File can be downloaded from the following location : " + filePath;      return Response.status(200).entity(output).build();  }  private void saveFile(InputStream uploadedInputStream,         String serverLocation) {     try {             OutputStream outputStream = new FileOutputStream(new      File(serverLocation));             int read = 0;             byte[] bytes = new byte[1024];              outputStream = new FileOutputStream(new File(serverLocation));             while ((read = uploadedInputStream.read(bytes)) != -1) {                 outputStream.write(bytes, 0, read);             }             outputStream.flush();             outputStream.close();         } catch (IOException e) {             e.printStackTrace();         }     }    
like image 575
Ernie Avatar asked Mar 20 '14 06:03

Ernie


1 Answers

You could do the saving to the server in lesser number of lines using nio

java.nio.file.Path outputPath = FileSystems.getDefault().getPath(<upload-folder-on-server>, fileName); Files.copy(fileInputStream, outputPath); 

Also, if you're using 0.7.0-rc2, you will need this dependency in your pom.xml

<dependency> <groupId>com.sun.jersey.contribs</groupId> <artifactId>jersey-multipart</artifactId> <version>1.18</version> </dependency> 
like image 62
stratzoomer Avatar answered Sep 19 '22 09:09

stratzoomer