文件上传(注解方式)----2018-09-25

2018-09-26  本文已影响0人  Mango_lxh

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
   
  <!-- Standard Action Servlet Configuration (with debugging) -->
  <servlet>
    <servlet-name>spring</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/spring-servlet.xml</param-value>  默认
    </init-param>
    -->
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>spring</servlet-name>
    <url-pattern>*.do</url-pattern>
</servlet-mapping>
  
</web-app>

spring-servlet.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:p="http://www.springframework.org/schema/p"     
        xmlns:context="http://www.springframework.org/schema/context"     
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd   
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd   
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">


     <!-- 启用spring mvc 注解 -->
    <context:annotation-config />

    <!-- 设置使用注解的类所在的jar包 -->
    <context:component-scan base-package="com.asm"></context:component-scan>

    <!-- 完成请求和注解POJO的映射 -->
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" />

    <!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
     <property name="prefix" value="/WEB-INF/page/" />            
     <property name="suffix" value=".jsp" />
     </bean>  

    <bean id="multipartResolver"  
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >  
    <property name="defaultEncoding" value="gbk"/> <!-- 默认编码 (ISO-8859-1) -->  
    <property name="maxInMemorySize" value="10240"/> <!-- 最大内存大小 (10240)-->  
    <property name="uploadTempDir" value="/upload/"/> <!-- 上传后的目录名 (WebUtils#TEMP_DIR_CONTEXT_ATTRIBUTE) -->  
    <property name="maxUploadSize" value="-1"/> <!-- 最大文件大小,-1为无限止(-1) -->  
    </bean>
     
 </beans> 

FileUploadController类

package com.asm;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Date;

import javax.servlet.ServletContext;

import org.springframework.stereotype.Controller;
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.context.ServletContextAware;
import org.springframework.web.multipart.commons.CommonsMultipartFile;


@Controller
public class FileUploadController implements ServletContextAware {

    private ServletContext servletContext;
    
 
    public void setServletContext(ServletContext  context) {
        this.servletContext  = context;
    }
    
    @RequestMapping(value="/upload.do")
    public String handleUploadData(String name,@RequestParam("myFile")CommonsMultipartFile file){
        if (!file.isEmpty()) {
               String path = this.servletContext.getRealPath("/upload/");  //获取本地存储路径
               System.out.println(path);
               String fileName = file.getOriginalFilename();  //拿到上传文件名
               String fileType = fileName.substring(fileName.lastIndexOf(".")+1);  //拿到上传文件扩展名
               System.out.println(fileName); 
               System.out.println(fileType); 
               File file1 = new File(path,fileName); //新建一个文件
                 try {
                byte[] b= file.getBytes();//将上传的文件写入新建的文件中
                FileOutputStream fos = new FileOutputStream(file1);
                fos.write(b);
                fos.flush();
                fos.close();
               } catch (Exception e) {
                    e.printStackTrace();
               }
               return "redirect:upload_ok.jsp";
            }else{
                return "redirect:upload_error.jsp";
            }
    }
}

建立upload.jsp页面 代码如下:

 <form action="upload.do"  method="post" enctype="multipart/form-data">
名字:<input type="text" name="name" /><br>
上传的文件:<input type="file" name="file" /><br>
<input type="submit" />
</form>
上一篇下一篇

猜你喜欢

热点阅读