使用Vertx.io框架为多部件文件上载编写后API

时间:2016-08-29 23:46:19

标签: java multipart vert.x

我正在使用vertx.io编写用于多部分文件上传的代码。

在Spring启动时,我的代码如下。我想在vertex.io中写相似的东西

@RequestMapping(value = "/upload", headers=("content-type=multipart/*") ,method = RequestMethod.POST)
public ImportExportResponse upload(@RequestParam("file") MultipartFile inputFile){
    log.info(" upload service method starts  ");
    ImportExportResponse response = new ImportExportResponse();
    FileOutputStream fileOutputStream=null;
    try{
        File outputFile = new File(FILE_LOCATION+inputFile.getOriginalFilename());
        fileOutputStream = new FileOutputStream(outputFile);
        fileOutputStream.write(inputFile.getBytes());   
        fileOutputStream.close();

        response.setStatus(ImportExportConstants.ResponseStatus.SUCCESS.name());
        response.setErrorMessage(EMPTY);

    }catch (Exception e) {
        log.error("Exception while upload the file . "+e.getMessage());
        response.setStatus(ImportExportConstants.ResponseStatus.ERROR.name());
        response.setErrorMessage(errorMap.get(SYSTEM_ERROR_CODE));          
    }
    log.info(" upload service method ends. file is copied to a temp folder ");
    return response;
}

1 个答案:

答案 0 :(得分:5)

这是相同的但是在vert.x:

Router router = Router.router(vertx);

// Enable multipart form data parsing
router.post("/upload").handler(BodyHandler.create()
  .setUploadsDirectory(FILE_LOCATION));

// handle the form
router.post("/upload").handler(ctx -> {
  // in your example you only handle 1 file upload, here you can handle
  // any number of uploads
  for (FileUpload f : ctx.fileUploads()) {
    // do whatever you need to do with the file (it is already saved
    // on the directory you wanted...
    System.out.println("Filename: " + f.fileName());
    System.out.println("Size: " + f.size());
  }

  ctx.response().end();
});

有关更多示例,您始终可以看到vertx-examples回购。