• Spring MVC文件上传处理


    以下示例显示如何在使用Spring Web MVC框架的表单中上传文件和处理。首先使用Eclipse IDE来创建一个WEB工程,实现一个上传文件并保存的功能。并按照以下步骤使用Spring Web Framework开发基于动态表单的Web应用程序:

    1. 创建一个名称为 FileUpload 的动态WEB项目。
    2. 在 com.yiibai.springmvc 包下创建两个Java类FileModelFileUploadController
    3. jsp子文件夹下创建两个视图文件:fileUpload.jsp 和 success.jsp
    4. WebContent文件夹下创建一个文件夹:temp
    5. 下载Apache Commons FileUpload库:commons-fileupload.jarApache Commons IO库:commons-io.jar。把它们放在CLASSPATH中。
    6. 最后一步是创建所有源和配置文件的内容并运行应用程序,详细如下所述。

    完整的项目文件目录结构如下所示 -

    FileModel.java 的代码如下所示 -

    package com.yiibai.springmvc;
    
    import org.springframework.web.multipart.MultipartFile;
    
    public class FileModel {
       private MultipartFile file;
    
       public MultipartFile getFile() {
          return file;
       }
    
       public void setFile(MultipartFile file) {
          this.file = file;
       }
    }
    
    Java

    FileUploadController.java 的代码如下所示 -

    package com.yiibai.springmvc;
    
    import java.io.File;
    import java.io.IOException;
    
    import javax.servlet.ServletContext;
    
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.ModelMap;
    import org.springframework.util.FileCopyUtils;
    import org.springframework.validation.BindingResult;
    import org.springframework.validation.annotation.Validated;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.servlet.ModelAndView;
    
    @Controller
    public class FileUploadController {
    
       @Autowired
       ServletContext context; 
    
       @RequestMapping(value = "/fileUploadPage", method = RequestMethod.GET)
       public ModelAndView fileUploadPage() {
          FileModel file = new FileModel();
          ModelAndView modelAndView = new ModelAndView("fileUpload", "command", file);
          return modelAndView;
       }
    
       @RequestMapping(value="/fileUploadPage", method = RequestMethod.POST)
       public String fileUpload(@Validated FileModel file, BindingResult result, ModelMap model) throws IOException {
          if (result.hasErrors()) {
             System.out.println("validation errors");
             return "fileUploadPage";
          } else {            
             System.out.println("Fetching file");
             MultipartFile multipartFile = file.getFile();
             String uploadPath = context.getRealPath("") + File.separator + "temp" + File.separator;
             //Now do something with file...
             FileCopyUtils.copy(file.getFile().getBytes(), new File(uploadPath+file.getFile().getOriginalFilename()));
             String fileName = multipartFile.getOriginalFilename();
             model.addAttribute("fileName", fileName);
             return "success";
          }
       }
    }
    
    Java

    FileUpload-servlet.xml 的代码如下所示 -

    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="
       http://www.springframework.org/schema/beans     
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
       http://www.springframework.org/schema/context 
       http://www.springframework.org/schema/context/spring-context-3.0.xsd">
    
        <context:component-scan base-package="com.yiibai.springmvc" />
    
        <bean
            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" />
    </beans>
    
    XML

    这里的第一个服务方法fileUploadPage(),我们已经在名为“command”的ModelAndView对象中传递了一个空的FileModel对象,因为如果JSP文件中使用<form:form>标签,spring框架期望一个名称为“command”的对象。 因此,当调用fileUploadPage()方法时,它返回fileUpload.jsp视图。
    第二个服务方法fileUpload()将根据 URL => FileUpload/fileUploadPage上的POST方法进行调用。将根据提交的信息准备要上传的文件。最后从服务方法返回“success”视图,这将呈现success.jsp视图。

    fileUpload.jsp 的代码如下所示 -

    <%@ page contentType="text/html; charset=UTF-8"%>
    <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
    <html>
    <head>
    <title>Spring MVC上传文件示例</title>
    </head>
    <body>
        <form:form method="POST" modelAttribute="fileUpload"
            enctype="multipart/form-data">
          请选择一个文件上传 : 
          <input type="file" name="file" />
            <input type="submit" value="提交上传" />
        </form:form>
    </body>
    </html>
    
    HTML

    这里使用带有value =“fileUpload”modelAttribute属性来映射文件用服务器模型上传控件。

    success.jsp 的代码如下所示 -

    <%@ page contentType="text/html; charset=UTF-8"%>
    <html>
    <head>
    <title>Spring MVC上传文件示例</title>
    </head>
    <body>
        文件名称 :
        <b> ${fileName} </b> - 上传成功!
    </body>
    </html>
    
    HTML

    完成创建源和配置文件后,发布应用程序到Tomcat服务器。

    现在启动Tomcat服务器,现在尝试访问URL => http://localhost:8080/FileUpload/fileUploadPage ,如果Spring Web应用程序没有问题,应该看到以下结果:

    提交所需信息后,点击提交按钮提交表单。 如果 Spring Web 应用程序没有问题,应该看到以下结果:

  • 相关阅读:
    mysql主从延迟高的原因
    OpenStack云平台网络模式及其工作机制
    maps.reg
    dnion的remap.conf文件
    linux的tar命令
    traffic server文件目录
    records.config文件参数解释
    VNC配置
    KVM详情
    cache.config文件配置模板
  • 原文地址:https://www.cnblogs.com/borter/p/9519625.html
Copyright © 2020-2023  润新知