zoukankan      html  css  js  c++  java
  • Upload and Download File using Java

    1.Upload Control

    ①Apache的Commons FileUpload

    ②JavaZoom的UploadBean

    ③JspSmartUpload


    2.Download FileUpload Commons Control

    Official Website:http://commons.apache.org/fileupload/

    Download Commons IO Control

    Official Website:http://commons.apache.org/io/


    3.使用实例

    步骤一:创建文件上传的页面:fileUpload.jsp

    注意表单的 enctype 属性,这个设置很重要,详情请见:http://www.cnblogs.com/yinger/archive/2011/09/11/2173689.html

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>文件上传</title>
      </head>
      <body>
          <form action="<%=request.getContextPath() %>/servlet/FileUploadServlet" method="post" enctype="multipart/form-data" >
            上传人名:<input type="text" name="name" /><br/>      
              上传文件:<input type="file" name="file" /><br/>
              <input type="submit" name="submit" value="提交" />
          </form>
      </body>
    </html>


    步骤二:创建处理文件上传的servlet:fileUploadServlet

    package com.angelo.servlet;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.Iterator;
    import java.util.List;
    import javax.servlet.ServletConfig;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.commons.fileupload.FileItem;
    import org.apache.commons.fileupload.disk.DiskFileItemFactory;
    import org.apache.commons.fileupload.servlet.ServletFileUpload;
    
    public class FileUploadServlet extends HttpServlet {
        
        private ServletContext sc;
        private String savePath;
        private static final long serialVersionUID = 151650843430214502L;
    
        public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doPost(request, response);
        }
    
        public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            
            request.setCharacterEncoding("UTF-8");
        
            DiskFileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(factory);//通过工厂生成一个处理文件上传的servlet对象
            
            try {
                List items = servletFileUpload.parseRequest(request);//解析request
                Iterator iterator = items.iterator();
                while (iterator.hasNext()) {
                    FileItem item = (FileItem) iterator.next();
                    if(item.isFormField()){//表单的参数字段
                        System.out.println("表单的参数名称:"+item.getFieldName()+",表单的参数值:"+item.getString("UTF-8"));
                    }else {
                        if(item.getName()!=null && !item.getName().equals("")){//一个上传的文件
                            System.out.println("文件的名称:"+item.getName());
                            System.out.println("文件的大小:"+item.getSize());
                            System.out.println("文件的类型:"+item.getContentType());
                            
                            File tempFile = new File(item.getName());//getName得到的文件名称包含了它在客户端的路径
                            File file = new File(sc.getRealPath("/")+savePath,tempFile.getName());
                            item.write(file);//将上传的文件写入到file中
                            
                            request.setAttribute("message", "上传文件成功!");
                        }else{
                            request.setAttribute("message", "没有选择上传文件!");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                request.setAttribute("message", "上传文件失败!");
            }
            
            request.getRequestDispatcher("/fileUploadResult.jsp").forward(request, response);//转向,输出结果
        }
    
        @Override
        public void init(ServletConfig config) throws ServletException {
            savePath = config.getInitParameter("savePath");
            sc = config.getServletContext();        
        }
        
    }


    步骤三:修改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" xmlns:web=http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd 
    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></display-name>
      <servlet>
        <description>This is the description of my J2EE component</description>
        <display-name>This is the display name of my J2EE component</display-name>
        <servlet-name>FileUploadServlet</servlet-name>
        <servlet-class>com.yinger.servlet.FileUploadServlet</servlet-class>
        <init-param> <!-- Servlet的初始化参数,配置上传文件的保存路径,这里是当前应用的uplods目录下 -->
        <param-name>savePath</param-name>
        <param-value>uploads</param-value>
        </init-param>
      </servlet>
    
      <servlet-mapping>
        <servlet-name>FileUploadServlet</servlet-name>
        <url-pattern>/servlet/FileUploadServlet</url-pattern>
      </servlet-mapping>
      <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
      </welcome-file-list>
    </web-app>


    同时在项目的根目录下创建文件夹 uploads (可以就在WebRoot中创建)

    步骤四:创建显示上传结果的页面:fileUploadResult.jsp

    <%@ page language="java" pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>文件上传</title>
      </head>
      <body>
      <p>
          ${requestScope['message'] }<br/>
      </p>
      </body>
    </html>
    


  • 相关阅读:
    命令行环境下简单实用的工具——重定向&管道
    阿里2014校招笔试题(南大)——利用thread和sleep生成字符串的伪随机序列
    Pooled Allocation(池式分配)实例——Keil 内存管理
    modelsim数据导出用于matlab绘图
    顺序块和并行块
    初入博园
    数字图像处理实验(7):PROJECT 04-03 , Lowpass Filtering 标签: 图像处理MATLAB 2017-05-25 09:30 109人
    杭电acm刷题(3):1062,Text Reverse 标签: 杭电acm 2017-05-15 08:26 126人阅读 评论(0)
    杭电ACM刷题(2):1005,Number Sequence 标签: 杭电acmC语言 2017-05-11 22:43 116人阅读
    数字图像处理实验(6):PROJECT 04-02,Fourier Spectrum and Average Value 标签: 图像处理MATLABfft 2017-05-07 23:1
  • 原文地址:https://www.cnblogs.com/yefengmeander/p/2887548.html
Copyright © 2011-2022 走看看