【问题标题】:Writing a post API for Multi Part File Upload using Vertx.io framework使用 Vertx.io 框架编写用于多部分文件上传的帖子 API
【发布时间】:2017-01-06 02:36:40
【问题描述】:

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

在 Spring Boot 中,我的代码如下。我想在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;
}

【问题讨论】:

    标签: java multipart vert.x


    【解决方案1】:

    这里是一样的,但在 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 repo。

    【讨论】:

    • 感谢您的帮助。我可以上传文件并更改目录,但现在如何添加文件大小不应超过 5MB 的约束。如果大于 5 MB,则不应将文件存储在目录中。
    • 为此使用 .setBodyLimit()
    • 当我上传文件时。这个方法fileUpload.uploadedFileName();正在给我完整位置的完整路径 例如:C:\Users\\fileToBeStored\baf1005d-d000-4e8f-b590-f97805b3969c 。我想要而不是完整的目录路径,它应该返回我 baf1005d-d000-4e8f-b590-f97805b3969c 。我该怎么做?
    • 您始终可以从字符串中创建一个java.io.File 对象并提取您需要的内容。
    • 现在假设我正在执行多个文件上传,如果文件大小大于 5 MB,它应该跳过文件以存储在物理位置。 if (fileUpload.size()>5000000){ errorMsg="文件大于 5MB ."+size;删除文件上传();或跳过该特定文件}
    猜你喜欢
    • 2011-01-25
    • 2013-01-23
    • 1970-01-01
    • 1970-01-01
    • 2011-09-12
    • 1970-01-01
    • 2014-06-28
    • 2016-05-15
    • 2023-03-19
    相关资源
    最近更新 更多