Dropwizard file upload

后端 未结 3 994
野的像风
野的像风 2021-02-01 18:36

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.

   
3条回答
  •  孤独总比滥情好
    2021-02-01 19:25

    Ensure that you add dropwizard-forms dependency to your pom.xml

    
        io.dropwizard
        dropwizard-forms
        ${dropwizard.version}
        pom
    
    

    Your resource seems good, Anyhow I've uploaded an example project for uploading files with Dropwizard - https://github.com/juanpabloprado/dw-multipart

    @POST
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(
            @FormDataParam("file") InputStream uploadedInputStream,
            @FormDataParam("file") FormDataContentDisposition fileDetail) throws MessagingException, IOException {
    
        String uploadedFileLocation = "C:/Users/Juan/Pictures/uploads/" + fileDetail.getFileName();
    
        // save it
        writeToFile(uploadedInputStream, uploadedFileLocation);
        String output = "File uploaded to : " + uploadedFileLocation;
        return Response.ok(output).build();
    }
    
    // save uploaded file to new location
    private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) throws IOException {
        int read;
        final int BUFFER_LENGTH = 1024;
        final byte[] buffer = new byte[BUFFER_LENGTH];
        OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
        while ((read = uploadedInputStream.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        out.flush();
        out.close();
    }
    

提交回复
热议问题