如何在Dropwizard Project中使用Postman上传图像?

时间:2019-02-11 04:44:48

标签: postgresql hibernate postman dropwizard

我正在使用Dropwizard框架进行Gradle项目开发,有人可以帮助我如何使用邮递员将图像上传到Dropwizard中。

预先感谢

1 个答案:

答案 0 :(得分:0)

我认为您可以使用以下代码来使用邮递员上传图片

@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response simpleUpload(@FormDataParam("file") InputStream uploadedInputStream,
                        @FormDataParam("file") FormDataContentDisposition fileDetail) {
 return Response.ok(saveTOFile(uploadedInputStream, fileDetail)).type(MediaType.TEXT_PLAIN_TYPE).build();
}

private String saveTOFile(InputStream uploadedInputStream, FormDataContentDisposition fileDetail) {
   final String UPLOAD_FOLDER="D://uploads/";
    String filelocation = UPLOAD_FOLDER + fileDetail.getFileName();
    File file = new File(filelocation);

    try {
        createFolderIfNotExists(UPLOAD_FOLDER);
    } catch (Exception e){
        Response.status(Response.Status.BAD_REQUEST).entity("could not create Folder").type(MediaType.TEXT_PLAIN_TYPE).build();
    }
    try {

        Files.copy(uploadedInputStream,file.toPath(),StandardCopyOption.REPLACE_EXISTING);

        OutputStream out=new FileOutputStream("D://"+fileDetail.getFileName());
        IOUtils.copyLarge(uploadedInputStream,out);
        IOUtils.closeQuietly(out);
        return "file copied to "+filelocation;
    } catch (IOException e) {
        e.printStackTrace();
        return "file did not copied";
    }
}
private void createFolderIfNotExists(String dirName)
        throws SecurityException {
    File theDir = new File(dirName);
    if (!theDir.exists()) {
        theDir.mkdir();
    }
}