SpringMVC文件上传

小编刚学了这个mvc图片上传,立马就做博客分享了,这个文件上传可以做成图片上传,压缩包上传等等,加一条判断就行了。小编在下面注释了。

 

导入依赖

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>javajdey47</groupId>
    <artifactId>javajdey47</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.8.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
        </dependency>
        <!-- jackson支持包 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-core</artifactId>
            <version>2.9.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-annotations</artifactId>
            <version>2.9.5</version>
        </dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.5</version>
        </dependency>

        <!--图片上传依赖-->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
    </dependencies>

</project>

编写springmvc.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!--配置视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--前缀-->
        <property name="prefix" value="/pages/"/>
        <!--后缀-->
        <property name="suffix" value=".jsp"/>
    </bean>

    <!--如果要实现文件上传,一定要配置springmvc的文件上传解析器
        注意: 文件上传解析器必须要有一个id值,并且id值是固定的-multipartResolver,不能修改名字multipartResolver
    -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!--maxUploadSize : 限制上传的文件最大的容量, 单位是字节-->
        <property name="maxUploadSize" value="10485760" /> <!--上传的文件最大不能超过10m-->
    </bean>



    <!--开启注解扫描-->
    <context:component-scan base-package="dt2008" />

    <!--开启注解驱动-->
    <mvc:annotation-driven />

</beans>

jsp页面(上传文件)

<%--
  Created by IntelliJ IDEA.
  User: ztl
  Date: 2020/2/15
  Time: 11:40
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload" method="post" enctype="multipart/form-data">
    <%--普通的文本表单项--%>
    用户名:<input type="text" name="userName"/><br/>
    <%--文件上传表单项--%>
    <input type="file" name="image"/><br/>
    <input type="submit" value="提交"/>
</form>
</body>
</html>

用MVC实现文件上传

package dt2008._05实现文件上传SpringMVC文件上传;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Controller
public class UploadController {

    //访问URL路径
    @RequestMapping("/upload")
    //MultipartFile image这里要跟前端的上传按钮name值一致才行
    public String upload2(HttpServletRequest request,String userName,MultipartFile image) throws IOException {
        System.out.println("接收到的userName:"+userName);
        //把上传文件写入images目录
        //1.利用ServletContext, 找到images的绝对路径
        String dirPath = request.getSession().getServletContext().getRealPath("/images");
        //String dirPath = new ApplicationHome(getClass()).getSource().getPath() + "/images/";
        //2. 判断目录是否存在,如果不存在直接创建该目录
        File dir = new File(dirPath);
        if(!dir.exists()){
            dir.mkdirs();
        }
        //3. 获取文件名
        // getOriginalFilename()  获取文件的原始的名字
        String fileName = image.getOriginalFilename();

        //4.得到文件的拓展名  1.jpg
        //可以在这里加判断是否图片还是什么文件来截止上传
        //String ext = fileName.substring(fileName.lastIndexOf("."));

        //5. 得到一个uuid作为文件的文件名
        String uuid = UUID.randomUUID().toString();

        //6. 重构文件名  uuid_1.jpg
        fileName = uuid+"_"+fileName;

        //3. 把上传的文件写入到images目录中
        File targetFile = new File(dir,fileName);
        ///  transferTo() 把上传的文件写出到指定目录中.
        image.transferTo(targetFile);

        //跳转成功页
        /*
            注意:因为springmvc.xml文件写了
                前缀:<property name="prefix" value="/pages/"/>
                后缀:<property name="suffix" value=".jsp"/>
            那就需要在web创建个pages文件夹,里面放success.jsp
            之所以没写后缀名,是因为springmvc.xml里的后缀默认写上了mvc
        */
        return "success";

    }

}

 

本站资源除特别声明外,转载文章请声明文章出处
东泰博客 » SpringMVC文件上传

发表评论