前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >springmvc文件上传/下载

springmvc文件上传/下载

作者头像
微醺
发布2019-01-17 12:46:19
1.7K0
发布2019-01-17 12:46:19
举报

文件上传

1,配置文件上传解析器

在springmvc-servlet.xml中配置

代码语言:javascript
复制
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 设置上传文件的最大尺寸为1MB -->
        <property name="maxUploadSize">
            <value>1048576</value>
        </property>
    </bean>

需要导入fileupload依赖包 io的包 com.springsource.org.apache.commons.fileupload-1.2.0.jar com.springsource.org.apache.commons.io-1.4.0.jar

2,编写前端页面代码,使用form表单上传

代码语言:javascript
复制
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/11/7
  Time: 15:43
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>文件上传</title>
  </head>

  <body>
  <form action="uploadFile" method="post" enctype="multipart/form-data">
  <input type="file" name="file"><br>
  <input type="submit" value="提交">
  </form>
  </body>
</html>

3,controller里面的代码,

一定使用MultipartFile file作为形参,能将前端传入的文件自动注入到该参数中。

代码语言:javascript
复制
@RequestMapping("/uploadFile")
    public String uploadFile(MultipartFile file){
        System.out.println(file.getContentType());//获取文件类型
        System.out.println(file.getSize());//获取文件大小
        System.out.println(file.getOriginalFilename());//获取文件原始名称
        System.out.println(file.getName());//input的name
        //把文件保存在指定路径(桌面)
        try {
            File desFile = new File("C:/Users/Administrator/Desktop/"+file.getOriginalFilename());
            FileUtils.copyInputStreamToFile(file.getInputStream(),desFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "index";
    }

4,使用ajax上传图片,动态显示在傍边的img标签中

ajax的特点:异步请求,局部刷新 前端加上jquary代码

代码语言:javascript
复制
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2018/11/9
  Time: 19:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <script type="text/javascript" src="jq.js"></script>
    <script type="text/javascript">
        $(function(){
            $("#file").change(function(){
               var data = new FormData($("#form")[0]);
                $.ajax({
                    type:"post",
                    url:"uploadFile1",
                    data:data,
                    cache:false,
                    processData:false,
                    contentType:false,
                    beforeSend:function(){
                    },
                    success:function(msg){
                        $("img").attr("src",msg);
                    },
                    error:function(){
                    }
                });
            });
        });
    </script>
</head>
<body>
<form method="post" enctype="multipart/form-data" id="form">
    <input type="file" name="file" id="file"><img style="width: 100px;height: 100px"><br>
</form>
</body>
</html>

controller代码

代码语言:javascript
复制
 @RequestMapping("/uploadFile1")
    @ResponseBody//局部刷新
    public String uploadFile1(MultipartFile file ,HttpServletRequest request){
        //把文件保存在指定路径
        String path = request.getServletContext().getRealPath("imgs");
        File destFile = new File(path+"/"+file.getOriginalFilename());
        try {
            InputStream in = file.getInputStream();
            FileUtils.copyInputStreamToFile(in,destFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String msg = "imgs/"+file.getOriginalFilename();
        return msg;
    }

5,文件下载

代码语言:javascript
复制
@RequestMapping("/download")
    @ResponseBody
    public void download(HttpServletResponse response) throws Exception{
        response.setHeader("content-Disposition","attachment;filename = a.jpg");
        OutputStream out = response.getOutputStream();
        FileInputStream in = new FileInputStream("D:\\file\\1.jpg");
        IOUtils.copy(in,out);
        in.close();
        out.close();
    }

直接访问/download就能下载文件,不过现在都不用这种方法下载了,大都使用html5的新特性下载文件。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年11月14日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 文件上传
    • 1,配置文件上传解析器
      • 2,编写前端页面代码,使用form表单上传
        • 3,controller里面的代码,
          • 4,使用ajax上传图片,动态显示在傍边的img标签中
            • 5,文件下载
            领券
            问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档