利用MultipartFile实现文件上传功能

 更新时间:2017年11月20日 15:48:33   作者:hbcui1984  
这篇文章主要为大家详细介绍了利用MultipartFile实现文件上传功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

在java中上传文件似乎总有点麻烦,没.net那么简单,记得最开始的时候用smartUpload实现文件上传,最近在工作中使用spring的MultipartFile实现文件上传,感觉挺简单,在这里和大家分享一下。

一.主要有两个java类,和一般的servlet放在一起即可.

1.FileUploadBean.java

package chb.demo.web;

import org.springframework.web.multipart.MultipartFile;

/**
 * @author chb
 *
 */
public class FileUploadBean {

  private MultipartFile file;

  public void setFile(MultipartFile file) {
    this.file = file;
  }

  public MultipartFile getFile() {
    return file;
  }
}

2.FileUploadController.java

package chb.demo.web;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;


/**
 * @author chb
 *
 */
public class FileUploadController extends SimpleFormController {
    
  protected ModelAndView onSubmit(
    HttpServletRequest request,
    HttpServletResponse response,
    Object command,
    BindException errors){
    
    try
    {
      // cast the bean
      FileUploadBean bean = (FileUploadBean) command;

      // let's see if there's content there
      MultipartFile file = bean.getFile();
                
      if (file == null) {
        throw new Exception("上传失败:文件为�空");  
      }
      if(file.getSize()>10000000)    
      {
        throw new Exception("上传失败:文件大小不能超过10M");      
      }
      //得到文件�名
      String filename=file.getOriginalFilename();    
      
      if(file.getSize()>0){        
        try {
          SaveFileFromInputStream(file.getInputStream(),"D:/",filename);
        } catch (IOException e) {
          System.out.println(e.getMessage());
          return null;
        }
      }
      else{
        throw new Exception("上传失败:上传文件不能为�空");
      }
      // well, let's do nothing with the bean for now and return:
      try {
        return super.onSubmit(request, response, command, errors);
        
      } catch (Exception e) {
        System.out.println(e.getMessage());
        return null;
      }
    }
    catch(Exception ex)
    {
      System.out.println(ex.getMessage());
      return null;
    }
  }  
  
  /**保存文件
   * @param stream
   * @param path
   * @param filename
   * @throws IOException
   */
  public void SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException
  {   
    FileOutputStream fs=new FileOutputStream( path + "/"+ filename);
    byte[] buffer =new byte[1024*1024];
    int bytesum = 0;
    int byteread = 0; 
    while ((byteread=stream.read(buffer))!=-1)
    {
      bytesum+=byteread;
      fs.write(buffer,0,byteread);
      fs.flush();
    } 
    fs.close();
    stream.close();   
  }    
}

二.配置文件中如下配置:

1.web.xml,利用spring mvc模式,大家应该都很熟悉了

  <servlet>
    <servlet-name>chb</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>chb</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

2.chb-servlet.xml,这里要配置映射,并可以设定最大可上传文件的大小

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
  <!-- Multi-Action 用来标识method的变量名定义-->
  <bean id="methodNameResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
    <property name="paramName">
      <value>action</value>
    </property>
    <property name="defaultMethodName">
      <value>index</value>
    </property>
  </bean>
  
  <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- one of the properties available; the maximum file size in bytes -->
    <property name="maxUploadSize" value="10000000"/>
  </bean>
  

  <bean id="handlerMapping" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping">
    <property name="mappings">
     <props>
      <prop key="/upload.do">fileUploadController</prop>
     </props>
    </property>
  </bean>
  
  <bean id="fileUploadController" class="chb.demo.web.FileUploadController">
    <property name="commandClass" value="chb.demo.web.FileUploadBean"/>
    <!-- 上传失败时跳转页面 -->
    <property name="formView" value="/user/err.jsp"/>
    <!-- 上传成功时跳转页面 -->
     <property name="successView" value="/user/confirmation.jsp"/>
  </bean>
</beans>

三.设定jsp页面

 <form id="form1" method="post" action="upload.do" enctype="multipart/form-data">        
  <tr>
    <td width="25%" align="right">上传文件:</td>
    <td><input id="file" type="file" NAME="file" style="width:300px;"></td>
  </tr>
  <tr align="center" valign="middle">
    <td height="60" colspan="2"><input type="submit" ID="BtnOK" value="确认上传"></td>
  </tr>
</form>  

ok,现在就可以上传文件了,挺简单吧?这里我只列出了基本步骤,至于具体的操作(比如中文问题)可能就需要大家自己再完善完善了.

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • java开发之Jdbc分页源码详解

    java开发之Jdbc分页源码详解

    这篇文章主要介绍了java开发之Jdb分页源码详解,需要的朋友可以参考下
    2020-02-02
  • IDEA java出现无效的源发行版14解决方案

    IDEA java出现无效的源发行版14解决方案

    这篇文章主要介绍了IDEA java出现无效的源发行版14解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-11-11
  • RocketMQ存储文件的实现

    RocketMQ存储文件的实现

    这篇文章主要介绍了RocketMQ存储文件的实现方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-07-07
  • Springboot中的@ComponentScan注解使用解析

    Springboot中的@ComponentScan注解使用解析

    这篇文章主要介绍了Springboot中的@ComponentScan注解使用解析,@ComponentScan用于类或接口上主要是指定扫描路径,spring会把指定路径下带有指定注解的类注册到IOC容器中,需要的朋友可以参考下
    2024-01-01
  • IDEA的Mybatis Log Plugin插件配置和使用详解

    IDEA的Mybatis Log Plugin插件配置和使用详解

    这篇文章主要介绍了IDEA的Mybatis Log Plugin插件配置和使用,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2020-09-09
  • Eclipse安装Free marker插件教程

    Eclipse安装Free marker插件教程

    这篇文章主要为大家详细介绍了Eclipse安装Free marker插件教程,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2016-11-11
  • springboot2版本无法加载静态资源问题解决

    springboot2版本无法加载静态资源问题解决

    这篇文章主要介绍了springboot2版本无法加载静态资源问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-11-11
  • springcloud config配置读取优先级过程详解

    springcloud config配置读取优先级过程详解

    这篇文章主要介绍了springcloud config配置读取优先级过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-09-09
  • elasticsearch索引的创建过程index create逻辑分析

    elasticsearch索引的创建过程index create逻辑分析

    这篇文章主要介绍了elasticsearch索引核心index create,索引的创建过程解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2022-04-04
  • 详解如何获取java中类的所有对象实例

    详解如何获取java中类的所有对象实例

    如何在运行时获取一个Java类的所有对象实例呢,本文给大家介绍一种底层实现的方式,基于jvmti,代码用C++实现,感兴趣的小伙伴可以跟随小编一起学习一下
    2023-10-10

最新评论