SpringMVC的文件上传

来源:互联网 发布:淘宝全钢左轮发令枪 编辑:程序博客网 时间:2024/04/27 12:32

我们以前用的都是IO流来实现文件的上传和下载,springMVC提供了文件的上传的方法

他的底层依然是IO流来实现的

第一步:我们配置好SpringMVC的环境之后,我们创建一个上传的页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %><html><head>    <title>上传</title></head><body><form method="post" action="/upload" enctype="multipart/form-data">    <input type="text" name="name"><br>    <input type="file" name="file"><br>    <input type="submit" name="提交"></form></body></html>
注意:如果你的jsp的页面放在WEB-INF的下面话我们要在spring-servlet.xml中配制视图解析器

  <!--配置视图解析器-->    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <property name="prefix" value="/WEB-INF/jsp/"/>        <property name="suffix" value=".jsp"/>    </bean>
这样就可以找到了你的jsp页面了

第二步:我们要创建controller来找到上传的页面和提交的action

package org.peter.controller;import org.apache.commons.io.FileUtils;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.multipart.MultipartFile;import java.io.File;import java.io.IOException;/** * Created by Lenovo on 2017/7/19. */@Controllerpublic class UploadController {    @RequestMapping(value = "/upload",method = RequestMethod.POST)    @ResponseBody    public void fileUpdate(String name , MultipartFile file){        System.out.println(name);        System.out.println(file);        try {            FileUtils.writeByteArrayToFile(new File("E:\\photoFile",file.getOriginalFilename()),file.getBytes());        } catch (IOException e) {            e.printStackTrace();        }    }    @RequestMapping("/f")    public String upload(){        return "upload";    }}
因为SpringMVC分装了一个工具类FileUtils,这个类中有个方法writeByteArrayToFile(), 就是以字节数组的新式上传.

第三步:很是简单,那就是配制一下文件的上传的大小,和一些配制,这些配制在spring-servlet.xml中

   <!--配置文件上传-->    <bean class="org.springframework.web.multipart.commons.CommonsMultipartResolver" id="multipartResolver">        <!--配置上传文件的大小-->        <property name="maxUploadSize">            <value>5242880</value>        </property>    </bean>

只需三步就搞定。


原创粉丝点击