上传文件

来源:互联网 发布:python 爬虫多进程 编辑:程序博客网 时间:2024/06/04 01:35
package controllers;


import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.Iterator;  
import javax.servlet.http.HttpServletRequest;  
import org.apache.commons.io.FileUtils;  
import org.springframework.http.HttpHeaders;  
import org.springframework.http.HttpStatus;  
import org.springframework.http.MediaType;  
import org.springframework.http.ResponseEntity;  
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.multipart.MultipartFile;  
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;  
@Controller  
public class fileController {
/** 
     * 采用spring提供的上传文件的方法
     *  
     * @author:yxl
     * @Title: upLoadFile 
     * @param @param file 
     * @param @param request 
     * @param @throws IllegalStateException 
     * @param @throws IOException 
     * @return void 
     * @date  
     * @throws 
     */  
    @RequestMapping(value = "/upLoadFile.do", method = RequestMethod.POST)  
    public void upLoadFile(HttpServletRequest request)  
            throws IllegalStateException, IOException {  
        // @RequestParam("file") MultipartFile file,  
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(  
                request.getSession().getServletContext());  
        // 判断 request 是否有文件上传,即多部分请求  
        if (multipartResolver.isMultipart(request)) {  
            // 转换成多部分request  
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;  
            // 取得request中的所有文件名  
            Iterator<String> iter = multiRequest.getFileNames();  
            while (iter.hasNext()) {  
                // 取得上传文件  
                MultipartFile f = multiRequest.getFile(iter.next());  
                if (f != null) {  
                    // 取得当前上传文件的文件名称  
                    String myFileName = f.getOriginalFilename();  
                    // 如果名称不为“”,说明该文件存在,否则说明该文件不存在  
                    if (myFileName.trim() != "") {  
                        // 定义上传路径  
                        String path = "D:\\hzfilms_images\\"  
                                + myFileName;  
                        File localFile = new File(path);  
                        f.transferTo(localFile);  
                    }  
                }  
            }  
        }  
    }  
    
    /*
     * 采用file.Transto 来保存上传的文件
     */
    @RequestMapping("fileUpload2")
    public String  fileUpload2(@RequestParam("file") CommonsMultipartFile file) throws IOException {
         long  startTime=System.currentTimeMillis();
        System.out.println("fileName:"+file.getOriginalFilename());
        String path="D:\\hzfilms_images\\"+new Date().getTime()+file.getOriginalFilename();
        File newFile=new File(path);
        //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
        file.transferTo(newFile);
        long  endTime=System.currentTimeMillis();
        System.out.println("方法二的运行时间:"+String.valueOf(endTime-startTime)+"ms");
        return "/success"; 
    }
    
    /*
     * 通过流的方式上传文件
     * @RequestParam("file") 将name=file控件得到的文件封装成CommonsMultipartFile 对象
     */
    @RequestMapping("fileUpload")
    public String  fileUpload(@RequestParam("file") CommonsMultipartFile file) throws IOException {
         
         
        //用来检测程序运行时间
        long  startTime=System.currentTimeMillis();
        System.out.println("fileName:"+file.getOriginalFilename());
         
        try {
            //获取输出流 
            OutputStream os=new FileOutputStream("D:\\hzfilms_images\\" +new Date().getTime()+file.getOriginalFilename());
            //获取输入流 CommonsMultipartFile 中可以直接得到文件的流
            InputStream is=file.getInputStream();
            int temp;
            //一个一个字节的读取并写入
            while((temp=is.read())!=(-1))
            {
                os.write(temp);
            }
           os.flush();
           os.close();
           is.close();
         
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        long  endTime=System.currentTimeMillis();
        System.out.println("方法一的运行时间:"+String.valueOf(endTime-startTime)+"ms");
        return "/success"; 
    }

}  




springxml

<?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"    
    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.0.xsd    
        http://www.springframework.org/schema/context     
        http://www.springframework.org/schema/context/spring-context-3.0.xsd  
        http://www.springframework.org/schema/mvc   
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">    
  
  
    <context:annotation-config />    
    <mvc:annotation-driven />  
    <context:component-scan base-package="controllers" />    
      
    <!-- 避免IE执行AJAX时,返回JSON出现下载文件 -->  
    <bean id="mappingJacksonHttpMessageConverter"  
        class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
        <property name="supportedMediaTypes">  
            <list>  
                <value>text/html;charset=utf-8</value>  
            </list>  
        </property>  
    </bean>  
  
  
    <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->  
    <bean  
        class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
        <property name="messageConverters">  
            <list>  
                <ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->  
            </list>  
        </property>  
    </bean>  
      
    <!-- 支持上传文件 -->  
    <bean id="multipartResolver"  
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver" >  
        <!-- 100M -->  
        <property name="maxUploadSize" value="104857600"></property>      
        <property name="defaultEncoding" value="utf-8"></property>     
    </bean>  
</beans>    



index.html


<!DOCTYPE html>  
<html>  
<head>  
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />  
</head>  
<body>  
   <form action="./upLoadFile.do" method="post" enctype="multipart/form-data">  
                 选择文件:<input type="file" name="file"/>  
                 <input type="submit" value="提交"/>  
   </form>  
   <form name="Form2" action="/SpringMVC006/fileUpload2" method="post"  enctype="multipart/form-data">
<h1>采用multipart提供的file.transfer方法上传文件</h1>
<input type="file" name="file">
<input type="submit" value="upload"/>
</form>
<form name="serForm" action="/SpringMVC006/fileUpload" method="post"  enctype="multipart/form-data">
<h1>采用流的方式上传文件</h1>
<input type="file" name="file">
<input type="submit" value="upload"/>
</form>
</body>  
</html>  


web.xml



<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>TestUpload</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
<filter>  
        <description>字符集过滤器</description>  
        <filter-name>encodingFilter</filter-name>  
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>  
        <init-param>  
            <description>字符集编码</description>  
            <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>  
    <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:spring.xml</param-value>    
        </init-param>      
    </servlet>    
    <servlet-mapping>    
        <servlet-name>springMVC</servlet-name>    
        <url-pattern>*.do</url-pattern>    
    </servlet-mapping>  
    <welcome-file-list>  
        <welcome-file>index.html</welcome-file>  
        <welcome-file>index.htm</welcome-file>  
        <welcome-file>index.jsp</welcome-file>  
        <welcome-file>default.html</welcome-file>  
        <welcome-file>default.htm</welcome-file>  
        <welcome-file>default.jsp</welcome-file>  
    </welcome-file-list>    
</web-app>    

原创粉丝点击