文件的上传

第一步:导入依赖,在pom.xml中配置

  <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
  </dependency>
  <dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
  </dependency>

第二步:配置文件上传解析器,在springMVC.xml中配置

<!--文件上传的解析器,使用spring表达式设置上传文件大小最大值-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="#{1024*1024}"/>
</bean>

第三步:修改表单,加入属性enctype="multipart/form-data"

  application/x-www-form-urlencoded不是不能上传文件,是只能上传文本格式的文件,multipart/form-data是将文件以二进制的形式上传,这样可以实现多种类型的文件上传。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="/save" method="post" enctype="multipart/form-data">
    用户名:<input type="text" name="username"/><br/>
    头像:<input type="file" name="file"/><br/>
    <input type="submit" value="保存"/>
</form>

<a href="/download?name=xxx.png">下载</a>

</body>
</html>

第四步:使用springMVC接收文件

@Controller
public class UploadController {
    //servletContext上下文对象,可以直接注入
    @Autowired
    private ServletContext servletContext;
    @RequestMapping("/save")
    public ModelAndView save(MultipartFile file, String username) throws Exception{
        //把文件对象,以流的方式写出到img的文件夹中
        String realpath = servletContext.getRealPath("/img");
        //创建保存到服务器的文件的路径,使用时间戳改变文件名,以免重名
        String path= realpath +"/"+ new Date().getTime() + file.getOriginalFilename();
        File newFile = new File(path);
        file.transferTo(newFile);
        return null;
    }
}

文件下载

SpringMVC并没有对文件下载做封装,还是使用原来的方式

@Controller
public class DownLoadController {
    @Autowired
    private ServletContext context;

    @RequestMapping("/download")
    public ModelAndView download(String name, HttpServletRequest request,HttpServletResponse response) throws Exception{
        //GET请求中文件名为中文时乱码处理
        name=new String(name.getBytes("ISO-8859-1"),"UTF-8");
        //设置响应头为下载文件,而不是直接打开
        response.setContentType("application/x-msdownload");
        //获取代理服务器信息,因为IE和其他浏览器的修改响应头的中文格式的方式不同
        String userAgent=request.getHeader("User-Agent");
        if(userAgent.contains("IE")){
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(name,"UTF-8"));
        }else{
            response.setHeader("Content-Disposition","attachment;filename="+new String(name.getBytes("UTF-8"),"ISO-8859-1"));
        }
        //把文件对象,以流的方式写出到img的文件夹中
        String realpath = context.getRealPath("/img");
        Files.copy(Paths.get(realpath,name),response.getOutputStream());
        return null;
    }

 

posted on 2019-09-14 19:13  幸福的小耗子  阅读(824)  评论(0编辑  收藏  举报