SpringMVC技术上传文件的源代码

来源:互联网 发布:java splitstring 编辑:程序博客网 时间:2024/06/06 00:51

这里一定要注意上传的路径!作者本人由于粗心大意,一直忘记新建一个空的upload文件夹,导致上传失败,找不到问题根源所在!终于恍然大悟!
项目中用到的jar包这里写图片描述

这是applicationContext.xml的配置文件内容

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xmlns:context="http://www.springframework.org/schema/context"    xmlns:jdbc="http://www.springframework.org/schema/jdbc"     xmlns:jee="http://www.springframework.org/schema/jee"    xmlns:tx="http://www.springframework.org/schema/tx"     xmlns:jpa="http://www.springframework.org/schema/data/jpa"    xmlns:util="http://www.springframework.org/schema/util"    xmlns:mvc="http://www.springframework.org/schema/mvc"    xsi:schemaLocation="        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd"><!-- 将Controller或DAO等组件扫描到Spring容器 -->    <context:component-scan         base-package="org.tarena"/><!-- 定义@RequestMapping的支持 --><mvc:annotation-driven/><!-- 定义ViewResover --><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">    <property name="prefix"         value="/WEB-INF/jsp/">    </property>    <property name="suffix" value=".jsp">    </property></bean><!-- 定义上传解析器,自动调用commons-fileupload.jar --><bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    <property name="maxUploadSize"         value="10240">    </property>    <property name="resolveLazily"         value="true">    </property></bean></beans>

src文件内容

package org.tarena.controller;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.HashMap;import java.util.Map;import javax.servlet.http.HttpServletRequest;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.multipart.MaxUploadSizeExceededException;import org.springframework.web.multipart.MultipartFile;import org.springframework.web.servlet.ModelAndView;@Controllerpublic class UploadController {    @RequestMapping("/toUpload")    public String toUpload(){        //进入upload.jsp        return "upload";    }    @RequestMapping("/upload")    public String upload(        @RequestParam("file") MultipartFile file,        HttpServletRequest req,Model model) throws Exception{        //TODO 将file保存到upload文件夹位置        System.out.println("上传文件:"+file);        //-----检查上传文件类型-------        //1.file.getOriginalFilename(),截取扩展名        //2.判断是否允许该类型,不允许,跳转到upload.jsp,        //带一个error消息出去,终止后面执行        //-------------------        String path = req.getSession()            .getServletContext()            .getRealPath("upload");        String filePath = path+File.separatorChar            +file.getOriginalFilename();        System.out.println(filePath);//      try{            //写文件操作            InputStream fis = file.getInputStream();            FileOutputStream fos =                 new FileOutputStream(                    new File(filePath));            byte[] bbs = new byte[1024];            int len = -1;            while(-1 != (len=fis.read(bbs))){                fos.write(bbs,0,len);            }            fos.close();            fis.close();            //将上传的文件放入模型,在ok显示            model.addAttribute("fname",                 file.getOriginalFilename());            return "ok";//进入ok.jsp//      }catch(Exception ex){//          ex.printStackTrace();//          return "error";//进入错误error.jsp//      }    }    @ExceptionHandler//处理Controller方法抛出的异常    public ModelAndView doException(            Exception ex){        Map<String, Object> map =             new HashMap<String, Object>();        if(ex instanceof MaxUploadSizeExceededException){            long maxSize =             ((MaxUploadSizeExceededException)ex)            .getMaxUploadSize();            map.put("error",             "上传的文件太大,不能超过"+maxSize/1024+"K");        }else{            map.put("error", "上传失败");        }        return new ModelAndView("upload",map);    }}

web.xml配置文件

<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5"     xmlns="http://java.sun.com/xml/ns/javaee"     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"><servlet>    <servlet-name>springmvc</servlet-name>    <servlet-class>org.springframework.web.servlet.DispatcherServlet    </servlet-class>    <init-param>    <param-name>contextConfigLocation</param-name>    <param-value>classpath:applicationContext.xml</param-value>    </init-param>    <load-on-startup>1</load-on-startup></servlet><servlet-mapping>    <servlet-name>springmvc</servlet-name>    <url-pattern>*.from</url-pattern></servlet-mapping><filter>    <filter-name>encodingfilter</filter-name>    <filter-class>org.springframework.web.filter.CharacterEncodingFilter    </filter-class>    <init-param>        <param-name>encoding</param-name>        <param-value>UTF-8</param-value>    </init-param></filter><filter-mapping>    <filter-name>encodingfilter</filter-name>    <url-pattern>/*</url-pattern></filter-mapping>  <welcome-file-list>    <welcome-file>index.jsp</welcome-file>  </welcome-file-list></web-app>

WEB-INF下jsp文件中的两个.jsp文件
ok.jsp

<%@ page import="java.util.*"     pageEncoding="UTF-8"    contentType="text/html;charset=UTF-8"%><html>  <head>  </head>    <body>   上传成功!   <a href="upload/${fname }">${fname }</a>  </body></html>

upload.jsp

<%@ page import="java.util.*"     pageEncoding="UTF-8"    contentType="text/html;charset=UTF-8"%><html>  <head>  </head>    <body>  <font color="red">${error }</font>   <form action="upload.from" method="post"     enctype="multipart/form-data">        <input type="file" name="file">        <input type="submit" value="上传">   </form>  </body></html>
0 0