zoukankan      html  css  js  c++  java
  • 上传文件和下载

    多文件上传

    第一步架包

    第二步

    package cn.happy.controller;
    
    import java.io.File;
    import java.io.IOException;
    
    import javax.servlet.http.HttpSession;
    
    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.RequestParam;
    import org.springframework.web.multipart.MultipartFile;
    
    
    @Controller
    public class FirstController {
    
          @RequestMapping("/second.do")
      public String doFirst(@RequestParam MultipartFile[] upload,HttpSession session){
            String dirctory = session.getServletContext().getRealPath("/upload");
            for (MultipartFile item : upload) {
                
                //2.文件名称
                String filename = item.getOriginalFilename();
                //加判定,拦截
                if (filename.endsWith(".jpg")||filename.endsWith(".png")) {
    
                    //3.做保存
                    File file=new File(dirctory,filename);
                    try {
                        item.transferTo(file);
                    }  catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                
            }
            return "/success.jsp";
          }
        
    
        
        @RequestMapping("/first.do")
        /**
         * 
         * @param upload   从客户端浏览上传过来的文件对象
         * @return
         */
        public String doFirst(MultipartFile upload,HttpSession session){
            //save到server上的一个具体的文件夹中。
    
            if (upload.getSize()>0) {
                //1.物理文件夹  
                String dirctory = session.getServletContext().getRealPath("/upload");
                //2.文件名称
                String filename = upload.getOriginalFilename();
                //加判定,拦截
                if (filename.endsWith(".jpg")||filename.endsWith(".png")) {
    
                    //3.做保存
                    File file=new File(dirctory,filename);
                    try {
                        upload.transferTo(file);
                    }  catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                
                return "/welcome.jsp";
            }
            else {
                return "/index.jsp";
            }
        }
    }

    第三步:配置文件

    <?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:aop="http://www.springframework.org/schema/aop" 
        xmlns:tx="http://www.springframework.org/schema/tx" 
        xmlns:mvc="http://www.springframework.org/schema/mvc" 
         xsi:schemaLocation="
            http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
            ">
         
            <!-- 配置包扫描器-->
           <context:component-scan base-package="cn.happy.controller"></context:component-scan>
           
           <!-- 文件上传解析器 -->
           <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
             <property name="defaultEncoding" value="utf-8"></property>
             <property name="maxUploadSize" value="500000000"></property>
           </bean>
           
           <!-- 需要配置注解驱动 -->
           <mvc:annotation-driven/>
    </beans>

    第四步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">
      <display-name></display-name>    
      
      <!-- 编码过滤器 -->
      <filter>
        <filter-name>CharacterEncoding</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>CharacterEncoding</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:applicationContext.xml</param-value>
        </init-param>
        <!-- TOmcat启动的时候,Servlet对象就存储到内存 正整数 -->
        <load-on-startup>1</load-on-startup>
      </servlet>
      
      <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
      </servlet-mapping>
     
      
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>

    第五步:多文件上传jsp页面

    <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
    <%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
    %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <base href="<%=basePath%>">
        
        <title></title>
        <script type="text/javascript" src="js/jquery-1.8.3.js"></script>
       
      </head>
      
      <body>
        <h1>多文件上传</h1>
        <form action="${pageContext.request.contextPath }/second.do" method="post" enctype="multipart/form-data">
                   文件1   <input type="file" name="upload"/>
                   文件2   <input type="file" name="upload"/>
                   <input type="submit"/>
        </form>
      </body>
    </html>

     文件下载

    package cn.happy.controller;
    
    import java.io.File;
    import java.io.IOException;
    
    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;
    @Controller
    public class DownFile {
        @RequestMapping(value="/download.do")
         public ResponseEntity<byte[]> download() throws IOException {    
             
                File file=new File("D:\hehe.jpg");  
                HttpHeaders headers = new HttpHeaders();    
                String fileName=new String("你好.jpg".getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题  
                headers.setContentDispositionFormData("attachment", fileName);   
                headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);   
                return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);    
            }    
        }  
        

    jsp

    <a href="${pageContext.request.contextPath }/download.do?hehe.png">下载</a>
  • 相关阅读:
    [转]HBASE 二级索引
    EPOCH, BATCH, INTERATION
    AMAZON数据集
    模拟ajax实现网络爬虫——HtmlUnit
    MySQL 数据库 varchar 到底可以存多少个汉字,多少个英文呢?我们来搞搞清楚
    maven: 打包可运行的jar包(java application)及依赖项处理
    webdriver 执行完毕关闭chromedriver进程
    windows下批量杀死进程
    系统进程死锁是什么原因如何让进程不死锁
    Data source rejected establishment of connection, message from server: "Too many connections"
  • 原文地址:https://www.cnblogs.com/lizeyang/p/6270389.html
Copyright © 2011-2022 走看看