文件上传

1,配置文件上传解析器

在springmvc-servlet.xml中配置

<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表单上传

<%--
  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作为形参,能将前端传入的文件自动注入到该参数中。

@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代码

<%--
  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代码

 @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,文件下载

@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的新特性下载文件。

12-15 07:53