一.主要有两个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,现在就可以上传文件了,挺简单吧?这里我只列出了基本步骤,至于具体的操作(比如中文问题)可能就需要大家自己再完善完善了.

MultipartFile实现文件上传的更多相关文章

  1. 利用spring的MultipartFile实现文件上传【原】

    利用spring的MultipartFile实现文件上传 主要依赖jar包 spring-web-3.0.6.RELEASE.jar 用到 (org.springframework.web.multi ...

  2. SpringMvc MultipartFile 图片文件上传

    spring-servlet.xml <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 --> <bean id="multipar ...

  3. SpringMVC 使用MultipartFile实现文件上传(转)

    http://blog.csdn.net/kouwoo/article/details/40507565 一.配置文件:SpringMVC 用的是 的MultipartFile来进行文件上传 所以我们 ...

  4. SpringMVC中使用 MultipartFile 进行文件上传下载及删除

    一:引入必要的包 <!--文件上传--> <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fil ...

  5. SpringMVC 使用 MultipartFile 实现文件上传

    该代码实现了文件上传和文本字段同时传递到后台进行处理的功能. 直接贴代码,中间涉及到的实体类就不贴了,和功能没啥关系的. Controller /** * 添加活动 * * @param req * ...

  6. MultipartFile 多文件上传的应用

    公司的项目很多地方要用到文件上传,以前的上传主要是用apache的fileupload ,使用的感受并不太好.今天试了试spring的MultipartFile,感觉还不错,封装的比较简洁. 当然,中 ...

  7. Spring MVC - MultipartFile实现文件上传(单文件与多文件上传)

    准备工作: 需要先搭建一个spirngmvc的maven项目 1.加入jar包 <dependency> <groupId>commons-fileupload</gro ...

  8. springMVC实现 MultipartFile 多文件上传

    1.Maven引入所需的 jar 包(或自行下载) <dependency> <groupId>commons-io</groupId> <artifactI ...

  9. 文件上传之 MultipartFile

    利用MultipartFile(组件)实现文件上传 在java中上传文件似乎总有点麻烦,没.net那么简单,记得最开始的时候用smartUpload实现文件上传,最近在工作中使用spring的Mult ...

随机推荐

  1. app保存图片到用户相册时闪退解决办法

    在iOS11中,app保存图片到用户相册时必须添加权限使用描述即NSPhotoLibraryAddUsageDescription,否则会闪退. 只需在info.plist—Property List ...

  2. jvm理论-字节码指令

    Java虚拟机的指令由一个字节长度的.代表着某种特定操作含义的数字(称为操作码,Opcode)以及跟随其后的零至多个代表此操作所需参数(称为操作数,Operands)而构成. 基本数据类型 1.除了l ...

  3. git中提示 please tell me who you are

    提示也就是需要你登录一下,确认你的身份,但是不要按照其提示输入,先输入命令git config user.name “username”,换行输入git config user.email “emai ...

  4. mybatis检测mysql表是否存在

    1.优先使用information_schema来检查,如果没有查询这个的权限则使用show tables来检查. mapper: import java.util.Map; import org.a ...

  5. UVA524 素数环 Prime Ring Problem

    题目OJ地址: https://www.luogu.org/problemnew/show/UVA524 hdu oj 1016:  https://vjudge.net/problem/HDU-10 ...

  6. 自己定义ViewGroup实现仿淘宝的商品详情页

    近期公司在新版本号上有一个须要. 要在首页加入一个滑动效果, 详细就是仿照X宝的商品详情页, 拉到页面底部时有一个粘滞效果, 例如以下图 X东的商品详情页,假设用户继续向上拉的话就进入商品图文描写叙述 ...

  7. WPF宝典Url

    https://sourceforge.net/directory/os:windows/https://archive.codeplex.com/ https://code.msdn.microso ...

  8. 在Visual Studio 2013中安装Mysql for EntityFramework

    1. 安装Visual Studio 20132. 下载mysql,安装mysql.3. 下载 mysql-for-visualstudio-1.2.7.msi, 下载链接:https://cdn.m ...

  9. PEP 492 -- Coroutines with async and await syntax 翻译

    因为工作中慢慢开始用python的协程,所以想更好的理解一下实现方式,故翻译此文 原文中把词汇表放到最后,但是我个人觉得放在最开始比较好,这样可以增加当你看原文时的理解程度 词汇表 原生协程函数 Na ...

  10. 基于Vue element-ui实现支持多级纵向动态表头的仿表格布局

    [本文出自天外归云的博客园] 需求图示如下,多级纵向动态表头表格: 我的思路是用element-ui的layout实现,做出一个仿造表格,能够支持动态的.多级的.纵向的表头: <template ...