0
点赞
收藏
分享

微信扫一扫

springboot RestController中文件上传的接口要点


1. 直接上代码

   @ResponseBody
@RequestMapping(value = "/examResultsImport", method = RequestMethod.POST)
String examResultsImport(@RequestParam("file") MultipartFile file){
File tempFile = null;
try {
tempFile = FileHelper.MultipartFile2File(file);
long fileSize = tempFile.length(); //以B为单位
} catch (Exception e) {

} finally {
//删除临时文件
if (null != tempFile){
tempFile.delete();
}
}
return null;
}

2. postman处理

  1. header,什么都不用处理,默认。

springboot RestController中文件上传的接口要点_springboot文件上传


2. body什么都不用做,保持默认。

springboot RestController中文件上传的接口要点_spring上传_02


3. 完成如图。

springboot RestController中文件上传的接口要点_spring上传_03

其他辅助类:
FileHelper.java

package com.mydomain.file;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
*
*/
public class FileHelper {
/**
* 转换
* @param multipartFile
* @return
*/
public static File MultipartFile2File(MultipartFile multipartFile) throws IOException {
// 获取文件名
String fileName = multipartFile.getOriginalFilename();
// 获取文件后缀
String prefix=fileName.substring(fileName.lastIndexOf("."));
// 用uuid作为文件名,防止生成的临时文件重复
final File file = File.createTempFile(UUID.randomUUID().toString(), prefix);
multipartFile.transferTo(file);
return file;
}
}

maven依赖:

  <dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<版本看着办>
</dependency>


举报

相关推荐

0 条评论