Java 使用Vertx.io框架编写用于多部分文件上传的post API
我正在使用vertx.io编写多部分文件上传的代码 在SpringBoot中,我的代码如下。我想在vertex.io中编写类似的代码Java 使用Vertx.io框架编写用于多部分文件上传的post API,java,multipart,vert.x,Java,Multipart,Vert.x,我正在使用vertx.io编写多部分文件上传的代码 在SpringBoot中,我的代码如下。我想在vertex.io中编写类似的代码 @RequestMapping(value = "/upload", headers=("content-type=multipart/*") ,method = RequestMethod.POST) public ImportExportResponse upload(@RequestParam("file") MultipartFile inputFile)
@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;
}
这里是相同的,但在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();
});
有关更多示例,您可以随时查看回购协议。谢谢您的帮助。我可以上传文件并更改目录,但现在如何添加文件大小不应超过5MB的限制。如果超过5 MB,则不应将文件存储在目录中。在上载文件时,请使用.setBodyLimit()进行此操作。此方法为fileUpload.uploadedFileName();正在为我提供完整路径和完整位置,例如:C:\Users\\filetobstored\baf1005d-d000-4e8f-b590-f97805b3969c。我想要的不是完整的目录路径,而是返回baf1005d-d000-4e8f-b590-f97805b3969c。我该怎么做呢?你总是可以从字符串中创建一个
java.io.File
对象,并提取你需要的内容。现在让我们假设,如果我正在进行多个fie上传,如果文件大小大于5 MB,它应该跳过该文件以物理方式存储。如果(fileUpload.size()>5000000){errorMsg=“文件大于5MB。”+size;deleteFileUploads();或跳过该特定文件}