Springboot实现文件上传和获取

Windows版

新建一个properties

# 文件的实体路径
image.path=C:\\Users\\Administrator\\IdeaProjects\\shitang\\img\\

# 待会要获取的IP地址
image.ip=localhost:8080

linux版本

# 文件的实体路径
image.path=/usr/web/shitangdemo/img/

# 待会要获取的IP地址
image.ip=localhost:8000

配置类,让properties的信息获取到这

@Configuration
@PropertySource(value = "file.properties")
public class imgpropertiesConfig implements WebMvcConfigurer {

    @Value("${image.path}")
    public String path;

    private static final String urlPath = "/img/**";

    @Value("${image.ip}")
    public String ip;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry)
    {
        registry.addResourceHandler(urlPath).addResourceLocations("file:"+path);
    }
}

提交Controller

@RestController
@CrossOrigin
public class imgController {
    @Autowired
    public imgpropertiesConfig config;

    @Autowired
    public ResponseUtil responseUtil;

    @RequestMapping("/img")
    public String getLocation()
    {
        return config.path;
    }

    @RequestMapping(value = "/addImage",method = RequestMethod.POST)
    public Map<String,Object> returnImg(@RequestPart("file") MultipartFile file,@RequestParam("foodname") String foodname)
    {
        // 获取顺带就把食品名给存进去了
        if(file.isEmpty())
        {
        	//自己创建的UTIL,实际上也就是返回失败的message
            return responseUtil.fileFail();
        }
        else
        {
//              String filePath = config.path+file.getOriginalFilename();
            System.out.println(config.path);
            String filePath = config.path+foodname+".jpg";
            File imgfile = new File(filePath);
            try{
                // 字节流获取
                FileOutputStream stream = new FileOutputStream(imgfile);
                byte[] bytes = file.getBytes();
                stream.write(bytes);
                // 关闭字节流
                stream.close();
                // 返回一个成功的信息和成功的url地址
                return responseUtil.fileSuccess(config.ip+"/img/"+foodname+".jpg");
            }
            catch (Exception e)
            {
                e.printStackTrace();
                return responseUtil.fileFail();
            }
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Spring Boot可以通过MultipartFile实现文件上传和下载。 文件上传: 1. 在Controller中添加一个POST请求处理方法,使用@RequestParam注解获取上传的文件。 2. 使用MultipartFile的transferTo()方法将文件保存到指定的位置。 3. 返回上传成功的信息。 文件下载: 1. 在Controller中添加一个GET请求处理方法,使用@RequestParam注解获取要下载的文件名。 2. 使用FileInputStream读取文件内容,并将内容写入到HttpServletResponse的输出流中。 3. 设置HttpServletResponse的Content-Disposition头部信息,指定文件名和下载方式。 4. 返回null,告诉Spring Boot不需要渲染任何视图。 示例代码: 文件上传: @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { try { // 保存文件到指定位置 file.transferTo(new File("D:/uploads/" + file.getOriginalFilename())); return "上传成功"; } catch (IOException e) { e.printStackTrace(); return "上传失败"; } } 文件下载: @GetMapping("/download") public ResponseEntity<byte[]> downloadFile(@RequestParam("filename") String filename) { try { // 读取文件内容 FileInputStream fis = new FileInputStream(new File("D:/uploads/" + filename)); byte[] content = new byte[fis.available()]; fis.read(content); fis.close(); // 设置Content-Disposition头部信息 HttpHeaders headers = new HttpHeaders(); headers.setContentDispositionFormData("attachment", filename); // 返回文件内容和头部信息 return new ResponseEntity<>(content, headers, HttpStatus.OK); } catch (IOException e) { e.printStackTrace(); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

NLeRnotfalled

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值