欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SSM(Spring+SpringMVC+Mybatis)框架文件上传

程序员文章站 2022-04-20 21:05:27
...

        本文使用的文件上传基于SSM框架中自带的文件上传机制,不懂原理,先将代码放在这里,只作测试及以后使用参考

        编写前台test.jsp

<%--
  Created by IntelliJ IDEA.
  User: 单继重
  Date: 2016/11/16
  Time: 11:05
  Description: 
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="${website}file/upload" method="post" enctype="multipart/form-data">
        <input type="file" name="file"><br><br>
        <input type="text" name="name">
        <input type="submit" value="上传">
    </form>
</body>
</html>

         简单的表单,并且有一个尝试获取的字段name

         后台Controller

package com.pandawork.web.controller;

import com.pandawork.web.spring.AbstractController;
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;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

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

/**
 * @author ShanJZ
 * @Description
 * @time 2016/11/16 11:01
 */
@Controller
@RequestMapping("/file")
public class FileController extends AbstractController{
    @RequestMapping(value = "/to/test")
    public String toTest(){
        return "/file/test";
    }
    @RequestMapping(value = "/upload")
    public String  springUpload(HttpServletRequest request, @RequestParam("name") String name) throws IllegalStateException, IOException
    {
        //将当前上下文初始化给  CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver=new CommonsMultipartResolver(
                request.getSession().getServletContext());
        //检查form中是否有enctype="multipart/form-data"
        if(multipartResolver.isMultipart(request)) {
            //将request变成多部分request
            MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
            //获取multiRequest 中所有的文件名
            Iterator iter=multiRequest.getFileNames();

            while(iter.hasNext()) {
                //一次遍历所有文件
                MultipartFile file=multiRequest.getFile(iter.next().toString());
                if(file!=null) {
                    String path="E:/springUpload"+"/"+file.getOriginalFilename();
                    //上传
                    file.transferTo(new File(path));
                }
            }
        }
        System.out.println(name);
        return "/success";
    }
}

         将文件保存至E盘下的springUpload文件夹下

注:代码参考该博客:http://www.cnblogs.com/fjsnail/p/3491033.html 顺便感谢博主(拱手)