SpringMVC实现文件上传

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

准备工作

1. 首先导入jar包:

SpringMVC实现文件上传_第1张图片

2. 在web.xml中配置如下:

<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>UploadFiledisplay-name>
    
    <welcome-file-list>
        <welcome-file>index.jspwelcome-file>
    welcome-file-list>

    
    <servlet>
        <servlet-name>springmvcservlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
        <init-param>
            <param-name>contextConfigLocationparam-name>
            <param-value>classpath:springmvc-servlet.xmlparam-value>
        init-param>
        <load-on-startup>1load-on-startup>
    servlet>
    <servlet-mapping>
        <servlet-name>springmvcservlet-name>
        <url-pattern>/url-pattern>
    servlet-mapping>
web-app>
3. springmvc-servlet.xml中添加上传的配置文件,如下:

<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">

    
    <context:component-scan base-package="com.lh.spring.controller" />

    
    <mvc:default-servlet-handler />

    
    <mvc:annotation-driven />

    
    <bean id="InternalResourceViewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="prefix" value="/WEB-INF/jsp/" />
        
        <property name="suffix" value=".jsp" />
    bean>

    
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        
        <property name="defaultEncoding" value="utf-8">property>
        
        <property name="maxUploadSize" value="9378819759000000">property>
        
        <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"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Upload Filetitle>
<style type="text/css">
* {
    margin: 0;
    padding: 0;
}
style>
head>
<body>

    <form action="UploadController/FileUpload" method="post"
        enctype="multipart/form-data" onsubmit="return FileIfNull()">
        <p style="text-align: center; margin: 100px;">
            Chosen file: <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中上传成功后调转的页面:

这里写图片描述

结果:

上传之前:

SpringMVC实现文件上传_第2张图片

上传成功之后:

SpringMVC实现文件上传_第3张图片

你可能感兴趣的:(spring,mvc,Java知识分享)