zoukankan      html  css  js  c++  java
  • springboot 文件上传下载

    关键点:

    1,使用 POST 请求
    2,consumes=MediaType.MULTIPART_FROM_DATA_VALUE
    3,@RequestParm 里面的字符串和前端 input 控件的 name 值一致

    上传文件示例:

    @PostMapping(value="/photos", consumes=MediaType.MULTIPART_FROM_DATA_VALUE)
    public void addPhoto(@RequestParm("photo") MultipartFile imgFile) throws Exception{
        // 保存文件
        FileOutputStream fos = new FileOutputStream("target/", imgFile.getOriginalFilename());
        IOUtils.copy(imgFile.getInputStream(), fos);
        fos.close();
      
    }

    带返回值上传文件示例(返回二进制数据,让用户看到上传的图片长什么样):

    @PostMapping(value="/icon", consumes=MediaType.MULTIPART_FROM_DATA_VALUE)
    public Byte[] addIcon(@RequestParm("photo") MultipartFile imgFile) throws Exception{
         // 用户上传文件的二进制数据
         InputStream is = imgFile.getInputStream();
         // 保存文件
         FileOutputStream fos = new FileOutputStream(new File("F:" + File.separator + imgFile.getOriginalFilename()));
         IOUtils.copy(is, fos);
         fos.close();
         // 返回文件
         return IOUtils.toByteArray(is);
        }

    下载文件示例:

    @GetMapping(value="/{userId}/photos", consumes=MediaType.MULTIPART_FROM_DATA_VALUE)
    public void getPhoto(@RequestParm("photo") MultipartFile imgFile) throws Exception{
           // 返回文件
           String userPhotoImgSrc = "src/test/10001.jpg";
           InputStream is = new FileInputStream(userPhotoImgSrc);
           return IOUtils.toByteArray(is);
    }
  • 相关阅读:
    不同浏览器的JS如何兼容?
    过滤器如何配置(javax.servlet.Filter)?
    hibernate中 dialect,lazy,inverse,cascade属性的用途?
    json注记
    php: $$str
    MySql计算字段的长度
    封装一个获取变量准确类型的函数
    JavaScript如何创建一个对象
    python+selenium自动登录163邮箱
    获取cookie
  • 原文地址:https://www.cnblogs.com/huanggy/p/9471845.html
Copyright © 2011-2022 走看看