- 创建实体类用于返回结果、
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 +
'}';
}
}
- 定义文件上传接口以及实现类
@Mapper
public interface FileMapper {
public FileReturn uploadFile(MultipartFile multipartFile);
}
@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);
}
}
- service 业务层
@Service
public class FileService {
@Resource
private FileServiceImpl fileServiceImpl;
public FileReturn uploadFile(MultipartFile multipartFile){
return fileServiceImpl.uploadFile(multipartFile);
}
}
- 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);
}
}
- postman 测试
文章参考 链接SpringBoot实现文件上传接口-阿里云开发者社区 (aliyun.com)
本文转载自: https://blog.csdn.net/p7477/article/details/127068377
版权归原作者 p7477 所有, 如有侵权,请联系我们删除。
版权归原作者 p7477 所有, 如有侵权,请联系我们删除。