Spring MVC文件上传教程

2021-07-20 06:05

阅读:641

YPE html PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd">

标签:depend   serve   source   filename   img   cfile   result   dispatch   for   

1- 介绍

这篇教程文章是基于 Spring MVC来实现文件的上传功能,这里主要是实现两个功能:1、上传单个文件并将其移动到对应的上传目录;2、一次上传多个文件并将它们存储在指定文件夹下,接下来我们一步步地实现。

2- 创建工程

  • File/New/Other..

技术分享图片
技术分享图片

技术分享图片

输入:

  • Group ID: com.yiibai
  • Artifact ID: SpringMVCFileUpload
  • Package: com.yiibai.springmvcfileupload

技术分享图片
这样,工程就被创建了,如下图所示:

 
技术分享图片
不要担心项目被创建时有错误消息。原因是,你还没有声明的Servlet库。

注意:

Eclipse 4.4 (Luna) 创建 Maven 项目结构可能会有错误,需要修复它。
技术分享图片
 

3- 配置Maven

  • pom.xml
4.0.0com.yiibai
    SpringMVCFileUpload
    war0.0.1-SNAPSHOTSpringMVCFileUpload Maven Webapphttp://maven.apache.orgjunit
            junit
            3.8.1testjavax.servlet
            javax.servlet-api
            3.1.0providedjavax.servlet
            jstl
            1.2javax.servlet.jsp
            jsp-api
            2.2providedorg.springframework
            spring-core
            4.1.4.RELEASEorg.springframework
            spring-web
            4.1.4.RELEASEorg.springframework
            spring-webmvc
            4.1.4.RELEASEcommons-fileupload
            commons-fileupload
            1.3.1commons-io
            commons-io
            2.4SpringMVCFileUploadorg.apache.tomcat.maven
                tomcat7-maven-plugin
                2.2

4- 配置Spring

 

技术分享图片
配置 web.xml.

SpringContextListener 将读取参数 contextConfigLocation 在配置文件:
  • WEB-INF/web.xml
Archetype Created Web Applicationspring-mvc
           org.springframework.web.servlet.DispatcherServlet
       1spring-mvc/contextConfigLocation
          /WEB-INF/root-context.xml
        org.springframework.web.context.ContextLoaderListener
配置 Spring MVC:
  • WEB-INF/spring-mvc-servlet.xml
/WEB-INF/pages/.jsp
  • WEB-INF/root-context.xml

5- Java类

  • MyFileUploadController.java
package com.yiibai.springmvcfileupload;
 
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
 
import javax.servlet.http.HttpServletRequest;
 
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.MultipartFile;
 
@Controller
public class MyFileUploadController {
 
    // Upload One File.
    @RequestMapping(value = "/uploadOneFile")
    public String uploadOneFileHandler() {
        // Forward to "/WEB-INF/pages/uploadOneFile.jsp".
        return "uploadOneFile";
    }
 
    // Upload Multi File.
    @RequestMapping(value = "/uploadMultiFile")
    public String uploadMultiFileHandler() {
        // Forward to "/WEB-INF/pages/uploadMultiFile.jsp".
        return "uploadMultiFile";
    }
 
    // uploadOneFile.jsp, uploadMultiFile.jsp submit to.
    @RequestMapping(value = "/doUpload", method = RequestMethod.POST)
    public String uploadFileHandler(HttpServletRequest request, Model model,
            @RequestParam("file") MultipartFile[] files) {
 
        // Root Directory.
        String uploadRootPath = request.getServletContext().getRealPath(
                "upload");
        System.out.println("uploadRootPath=" + uploadRootPath);
 
        File uploadRootDir = new File(uploadRootPath);
        //
        // Create directory if it not exists.
        if (!uploadRootDir.exists()) {
            uploadRootDir.mkdirs();
        }
        //
        List uploadedFiles = new ArrayList();
        for (int i = 0; i  0) {
                try {
                    byte[] bytes = file.getBytes();
 
                    // Create the file on server
                    File serverFile = new File(uploadRootDir.getAbsolutePath()
                            + File.separator + name);
 
                    // Stream to write data to file in server.
                    BufferedOutputStream stream = new BufferedOutputStream(
                            new FileOutputStream(serverFile));
                    stream.write(bytes);
                    stream.close();
                    //
                    uploadedFiles.add(serverFile);
                    System.out.println("Write file: " + serverFile);
                } catch (Exception e) {
                    System.out.println("Error Write file: " + name);
                }
            }
        }
        model.addAttribute("uploadedFiles", uploadedFiles);
        return "uploadResult";
    }
 
}

6- 视图(JSP)

  • uploadOneFile.jsp
Upload One File

Upload One File:

File to upload:
  • uploadMultiFile.jsp


Upload Multi File

Upload Multiple File:

File to upload (1):
File to upload (2):
File to upload (3):
File to upload (4):
File to upload (5):
  • uploadResult.jsp
 

     


Upload Result

Uploaded Files:

- ${file}

7- 运行应用程序

首先,运行应用程序之前,你需要构建整个项目。
右键单击该项目并选择:
技术分享图片
技术分享图片
 
运行配置:
 
技术分享图片
输入:
  • Name: Run SpringMVCFileUpload
  • Base directory: ${workspace_loc:/SpringMVCFileUpload}
  • Goals: tomcat7:run

技术分享图片
技术分享图片
技术分享图片

点击运行(Run):

  • http://localhost:8080/SpringMVCFileUpload/uploadOneFile
    技术分享图片
    技术分享图片
    技术分享图片
  • http://localhost:8080/SpringMVCFileUpload/uploadMultiFile
    技术分享图片
    技术分享图片a

Spring MVC文件上传教程

标签:depend   serve   source   filename   img   cfile   result   dispatch   for   

原文地址:https://www.cnblogs.com/borter/p/9519837.html


评论


亲,登录后才可以留言!