程序员最近都爱上了这个网站  程序员们快来瞅瞅吧!  it98k网:it98k.com

本站消息

站长简介/公众号

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

SpringBoot实现文件/图片的上传与下载

发布于2021-03-10 18:19     阅读(1451)     评论(0)     点赞(12)     收藏(2)


  • 导入依赖(pom.xml)

     <!-- 上传下载需要设计到的jar包 -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
        <!--servlet-api导入高版本的-->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
        <!-- 图片处理类 -->
        <dependency>
            <groupId>net.coobird</groupId>
            <artifactId>thumbnailator</artifactId>
            <version>0.4.8</version>
        </dependency>
  • 全局配置 application.properties

# 上传文件大小
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=5MB
  • 创建 WebMvcConfig 配置类  静态资源映射

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        ApplicationHome h = new ApplicationHome(getClass());
        File jarF = h.getSource();
        String dirPath = jarF.getParentFile().toString()+"/upload/";

        String os = System.getProperty("os.name");

        if (os.toLowerCase().startsWith("win")) {  //如果是Windows系统
            registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath);
        } else {
            registry.addResourceHandler("/upload/**").addResourceLocations("file:"+dirPath);
        }
    }

}
  • 文件或图片上传

  • 控制层
// 上传文件
    @ResponseBody
    @RequestMapping("/upload")
    public String fileUpload(@RequestParam("files") MultipartFile files) throws IOException {
//        // win系统 上传路径保存设置
//        // 获取项目路径
//        File projectPath = new File(ResourceUtils.getURL("classpath:").getPath());
//        // 绝对路径=项目路径+自定义路径
//        File pathFile = new File(projectPath.getAbsolutePath(), "static/upload/");
//        if (!pathFile.exists()) {
//            pathFile.mkdirs();
//        }
//        //上传文件地址
//        UUID uuid = UUID.randomUUID();
//        File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename());
//        files.transferTo(serverFile);
//
//        String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\\", "/");
//
//        return imgPath;

        // Linux服务器  上传路径保存设置
        // 项目路径  /home/www/
        File pathFile = new File("/home/www/upload/");
        if (!pathFile.exists()) {
            pathFile.mkdirs();
        }
        //上传文件地址
        UUID uuid = UUID.randomUUID();
        File serverFile = new File(pathFile, uuid + "_" + files.getOriginalFilename());
        files.transferTo(serverFile);

        String imgPath = ("/upload/" + uuid + "_" + files.getOriginalFilename()).replace("\\", "/");

        return imgPath;
    }
  • HTML页面    Ajax 无刷新上传 

<form action="" class="layui-form" enctype="multipart/form-data" method="post">
  <input type="hidden" name="blogImg" id="imgPath" value="">
  <div class="form-group">
    <label>图片上传</label>
    <input type='file' style='margin: 5px;' name='files' required><br>
    <button type="button" class="layui-btn" id="img_upload">上传图片</button>
  </div>
  <input type="submit">
</form>
  • JS

//普通图片上传
        $('#img_upload').click(function () {
            var formData = new FormData();
            //获取选择的文件
            $.each($('input[name="files"]'),function (index,item) {
                formData.append("files",item.files[0])
            });

            //发送异步请求
            $.ajax({
                method:'post',
                url: '[[@{/user/upload}]]', // 文件上传接口
                data:formData,
                processData: false,
                contentType:false,
                success:function (data) {
                    //成功返回触发的方法
                    $('#imgPath').val(data);
                    alert("上传成功");
                },
                //请求失败触发的方法
                error:function () {
                    alert("上传失败");
                }
            });
        });
  • 文件或图片下载

  • 控制层
@RequestMapping(value="/download")
public String downloads(HttpServletResponse response ,HttpServletRequest request) throws Exception{
   //要下载的图片地址
   String  path = request.getServletContext().getRealPath("/upload");
   String  fileName = "基础语法.jpg";

   //1、设置response 响应头
   response.reset(); //设置页面不缓存,清空buffer
   response.setCharacterEncoding("UTF-8"); //字符编码
   response.setContentType("multipart/form-data"); //二进制传输数据
   //设置响应头
   response.setHeader("Content-Disposition",
           "attachment;fileName="+URLEncoder.encode(fileName, "UTF-8"));

   File file = new File(path,fileName);
   //2、 读取文件--输入流
   InputStream input=new FileInputStream(file);
   //3、 写出文件--输出流
   OutputStream out = response.getOutputStream();

   byte[] buff =new byte[1024];
   int index=0;
   //4、执行 写出操作
   while((index= input.read(buff))!= -1){
       out.write(buff, 0, index);
       out.flush();
  }
   out.close();
   input.close();
   return null;
}
  • HTML页面  

<a href="/download">点击下载</a>

 

参考资料:狂神说SpringMVC:文件上传下载

原文链接:https://www.cnblogs.com/dmflysky/p/14450015.html




所属网站分类: 技术文章 > 博客

作者:西门费雪

链接:http://www.qianduanheidong.com/blog/article/34275/0636e463ea0b903e943e/

来源:前端黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

12 0
收藏该文
已收藏

评论内容:(最多支持255个字符)