SpringMVC实现文件上传

来源:互联网 发布:吊炸天软件下载 编辑:程序博客网 时间:2024/05/17 23:49

最近在做SpringMvc文件上传的功能实现,上网查了很多资料很多都不太符合理想,找啊找,终于找到一个可以用的,但是当把项目部署到云端服务器上的时候,上传500m以上的文件,传到一半就会崩掉,最终在Google上找到一种办法得以解决,可以支持1G的文件上传都不会崩掉。

准备工作

1. 首先导入jar包:

这里写图片描述

2. 在web.xml中配置如下:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns="http://xmlns.jcp.org/xml/ns/javaee"    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"    id="WebApp_ID" version="3.1">    <display-name>UploadFile</display-name>    <!--默认加载的页面-->    <welcome-file-list>        <welcome-file>index.jsp</welcome-file>    </welcome-file-list>    <!--SpringMVC的配置-->    <servlet>        <servlet-name>springmvc</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>classpath:springmvc-servlet.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>springmvc</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping></web-app>
3. springmvc-servlet.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-4.3.xsd        http://www.springframework.org/schema/mvc         http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">    <!-- scan the package and the sub package -->    <context:component-scan base-package="com.lh.spring.controller" />    <!-- don't handle the static resource -->    <mvc:default-servlet-handler />    <!-- if you use annotation you must configure following setting -->    <mvc:annotation-driven />    <!-- configure the InternalResourceViewResolver -->    <bean id="InternalResourceViewResolver"        class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <!-- prefix -->        <property name="prefix" value="/WEB-INF/jsp/" />        <!-- suffix -->        <property name="suffix" value=".jsp" />    </bean>    <!-- upload settings -->    <bean id="multipartResolver"        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">        <!-- setting default Encoding -->        <property name="defaultEncoding" value="utf-8"></property>        <!-- max Upload Size -->        <property name="maxUploadSize" value="9378819759000000"></property>        <!--max In Memory Size -->        <property name="maxInMemorySize" value="40960"></property>    </bean></beans>

代码如下:

Controller中对应的代码:
package com.lh.spring.controller;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.io.OutputStream;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;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.RequestParam;import org.springframework.web.multipart.commons.CommonsMultipartFile;/** * UploadController *  * @author huan * */@Controller@RequestMapping("/UploadController")public class UploadController {    /**     * 文件上传功能     *      * @param file     *            文件     * @param request     *            请求方式     * @return "UploadSuccess" 调转的页面     * @throws Exception     *             抛出的异常     */    /**     * 注解的意识是说value表示文件上传路径,method是表单对应的方法     */    @RequestMapping(value = "/FileUpload", method = RequestMethod.POST)    public String upload(@RequestParam(value = "file") CommonsMultipartFile file, HttpServletRequest request)            throws Exception {        // 获取当前的系统时间        long startTime = System.currentTimeMillis();        // 获取上传文件得名字        String uploadFileName = file.getOriginalFilename();        // 保存上传的文件,并告知服务器保存的路径        String savePath = request.getServletContext().getRealPath("/") + "upload".replaceAll("\\\\", "/");        // 上传文件得保存名字        String saveFileName = startTime + " " + uploadFileName.substring(uploadFileName.lastIndexOf("."));        // 判断该文件路径下的文件是否存在,,,,        /**         * 特别注意如果不加这几行代码就会出现文件上传一半崩掉的情况         */        File dirs = new File(savePath);        if (!dirs.exists()) {            dirs.mkdirs();        }        // 上传        file.transferTo(new File(dirs, saveFileName));        // 获取结束的时间        long endTime = System.currentTimeMillis();        System.out.println("上传所用的时间:" + (endTime - startTime) + "ms");        // 上传成功,这调转到WEB-INF下的UploadSuccess.jsp        return "UploadSuccess";    }}
对应的jsp代码:
<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%><!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"><title>Upload File</title><style type="text/css">* {    margin: 0;    padding: 0;}</style></head><body><!--注意:在form表单中,enctype="multipart/form-data"不能少,否则无法上传-->    <form action="UploadController/FileUpload" method="post"        enctype="multipart/form-data" onsubmit="return FileIfNull()">        <p style="text-align: center; margin: 100px;">            Chosen file:&nbsp;<input id="file" type="file" name="file"                width="120px"> <input type="submit" value="Upload">        </p>    </form></body><script type="text/javascript">    function FileIfNull() {        if (document.getElementById("file").value == "") {            alert("No file to chose");            return false;        } else {            return true;        }    }</script></html>
Controller中上传成功后调转的页面:

这里写图片描述

结果:

上传之前:

引用块内容

上传成功之后:

这里写图片描述

原创粉丝点击