1. 创建实体类用于返回结果、
public class FileReturn<T> implements Serializable {
private static final long serialVersionUID = -133233199901011121L;
private int resultCode;
private String msg;
private T data;
public FileReturn() {
}
public FileReturn(int resultCode, String msg, T data) {
this.resultCode = resultCode;
this.msg = msg;
this.data = data;
}
public int getResultCode() {
return resultCode;
}
public void setResultCode(int resultCode) {
this.resultCode = resultCode;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@Override
public String toString() {
return "FileReturn{" +
"resultCode=" + resultCode +
", msg='" + msg + '\'' +
", data=" + data +
'}';
}
}
2. 定义文件上传接口以及实现类
@Mapper
public interface FileMapper {
public FileReturn uploadFile(MultipartFile multipartFile);
}
文章来源:https://www.toymoban.com/news/detail-522553.html
@Service
public class FileServiceImpl implements FileMapper {
private static final Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);
@Override
public FileReturn uploadFile(MultipartFile multipartFile) {
// 文件保存路径
String filePath = "E:\\filepath";
// 文件名
String fileName = String.valueOf(System.currentTimeMillis());
File file = new File(filePath + File.separator + fileName);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
IOUtils.copy(multipartFile.getInputStream(),fileOutputStream);
System.out.println("====================file upload success====================");
}catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e) {
e.printStackTrace();
}finally {
try {
// 关闭
fileOutputStream.close();
}catch (IOException e) {
e.printStackTrace();
logger.error("文件关闭错误",e);
}
}
return new FileReturn<>(1,"文件上传成功",file);
}
}
3. service 业务层
@Service
public class FileService {
@Resource
private FileServiceImpl fileServiceImpl;
public FileReturn uploadFile(MultipartFile multipartFile){
return fileServiceImpl.uploadFile(multipartFile);
}
}
4. controller 控制层
@RestController
@RequestMapping(value = "/file")
public class FileController {
@Resource
private FileService fileService;
@RequestMapping("/upload")
public FileReturn uploadFile(@RequestParam("uploadFile")MultipartFile multipartFile){
return fileService.uploadFile(multipartFile);
}
}
5. postman 测试
文章参考 链接SpringBoot实现文件上传接口-阿里云开发者社区 (aliyun.com)文章来源地址https://www.toymoban.com/news/detail-522553.html
到了这里,关于基于SpringBoot 实现一个文件上传的API接口。并使用postman测试的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!