SpringMVC_单文件上传

第一步:导入文件上传的jar包

WebContent下创建个upload文件夹用于存放上传的文件

拷入jar包:

第二步:在springmvc.xml中配置文件上传相关配置

ctrl+shift+h 搜索CommonsMultipartResolver并右键复制链接,粘贴到bean中的class中

    <!-- 配置文件上传,id必须是这个multipartResolver,否则报错 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 配置文件上传的编码 -->
        <property name="defaultEncoding" value="utf-8"></property>
        <!-- 配置文件上传大小,value:字节大小,1024*1024就是1M,就是1048576 -->
        <property name="maxUploadSize" value="1048576"></property>
    </bean>

第三步:如果表单中有file控件,则必须指定enctype="multipart/form-data"

jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort() +request.getContextPath()+"/";
%>
<!DOCTYPE html>
<html>
<head>
    <base href="<%=basePath %>">
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>文件上传</title>
</head>
<body>
    <form action="<%=basePath %>singleFileUpload.shtml" method="post" enctype="multipart/form-data">
        <p>大头照:<input type="file" name="headImage">
        <p><input type="submit" value="上传">
    </form>
</body>
</html>

后台方法:

package cn.java.controller.front;

import java.io.File;

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

@Controller
public class TestController {

    /**
     * 单文件上传
     * 此方法是将文件上传到tomcat服务器中去,而不是保存到工程下。但工程下要在WebContent下创建upload文件夹
     * MultipartFile后面的必须是前台的file标签的name名相对应,用于将文件封装到对象中去
     * 
     */
    @RequestMapping("singleFileUpload")
    public void singleFileUpload(@RequestParam(name="headImage") MultipartFile file) throws Exception {
        
        //1.getOriginalFilename():获取上传文件的文件名
        String originalFilename = file.getOriginalFilename();
        //2.getName():这个获取的是<input type="file" name="headImage">中的name值:headImage
        String name = file.getName();
        System.out.println(originalFilename);
        System.out.println(name);
        //3.将文件保存到制定的目录下
        File filePath = new File("G:\Tools\JAVA\Eclipse\eclipse\Eclipse\springMVC\WebContent\upload\"+originalFilename);
        //4.把文件传到路径下
        file.transferTo(filePath);
    }
    
}

但路径要设置成动态的:

原文地址:https://www.cnblogs.com/lonske/p/9133938.html