Dropwizard file upload

怎甘沉沦 提交于 2019-12-02 19:06:48

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>

With Dropwizard 0.9.2 you have to add the dependency:

<dependency>
    <groupId>io.dropwizard</groupId>
    <artifactId>dropwizard-forms</artifactId>
    <version>${dropwizard.version}</version>
    <type>pom</type>
</dependency>

as well as register the multipart feature:

    environment.jersey().register(MultiPartFeature.class);

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

<dependency>
    <groupId>io.dropwizard</groupId>
    <artifactId>dropwizard-forms</artifactId>
    <version>${dropwizard.version}</version>
    <type>pom</type>
</dependency>

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();
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!