fastapi 传输文件存文件_文件上传的三种存储方式

本文介绍了使用FastAPI进行文件上传的三种方式:1) 本地存储,包括如何处理文件大小限制;2) 分布式文件系统FastDFS存储,详细讲述了配置和上传流程;3) 腾讯云对象存储COS,包括购买、配置、上传文件步骤。每种方式都提供了详细的代码实现和注意事项。
摘要由CSDN通过智能技术生成

1、本地上传

新建springboot项目,引入Thymeleaf、web相关依赖:

org.springframework.boot

spring-boot-starter

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-thymeleaf

在项目resource目录下新建templates文件夹并创建上传文件页面upload.html:

文件上传

选择文件:

创建success.html页面:

上传成功

再创建一个error.html页面

上传失败

新建uploadController

@Controller

@RequestMapping("/")

public class UploadController {

@Autowired

private UploadService uploadService;

@GetMapping("/upload")

public String to_upload(){

return "upload";

}

@PostMapping("/upload")

public String upload(MultipartFile file, HttpServletRequest request, Model model){

if (file!=null){

Map map=uploadService.localUpload(file);

model.addAllAttributes(map);

return "success";

}

model.addAttribute("fileName",file.getOriginalFilename());

model.addAttribute("msg","参数错误!");

return "error";

}

}

service

public interface UploadService {

Map localUpload(MultipartFile file);

}

service实现类

@Service

public class UploadServiceImpl implements UploadService {

@Override

public Map localUpload(MultipartFile file) {

Map resultMap=new HashMap<>();

try {

//原文件名加上时间戳作为上传后保存的文件名

String fileName=System.currentTimeMillis()+file.getOriginalFilename();

//指定目标文件名,此处将文件保存在项目的resource目录下,也可以保存在本地的其他目录下

String destFileName=System.getProperty("user.dir")

+File.separator+"src"

+File.separator+"main"

+File.separator+"resources"

+File.separator+"upload"

+File.separator+fileName;

//新建目标文件

File destFile = new File(destFileName);

//创建目标文件的存储路径

destFile.getParentFile().mkdirs();

//将前端接收的文件转化为目标文件

file.transferTo(destFile);

//将上传后的文件名和存储路径返回

resultMap.put("fileName",fileName);

resultMap.put("path",destFile);

} catch (IOException e) {

e.printStackTrace();

}

return resultMap;

}

}

在项目的resource目录新建application.yml配置文件,添加配置信息

server:

port: 8899 #端口

spring:

thymeleaf:

prefix: classpath:/templates/ #前端页面文件路径

suffix: .html #前端页面文件后缀名

启动项目,浏览器输入http://localhost:8899/upload

选择一张名为test.jpg的图片后提交

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值