zoukankan      html  css  js  c++  java
  • servlet3.0文件上传与下载

    描述:文件上传与下载是在JavaEE中常见的功能,实现文件上传与下载的方式有多种,其中文件上传的方式有:

    (1)commons-fileupload:

    (2)Servlet 3.0 实现文件上传

    (3)Ajax异步文件上传

    1、文件上传的要求:

    (1)form表单method请求方式设置为post(post请求方式不支持)

    (2)声明form表单属性:enctype="multipart/form-data",设置其数据格式二二进制

    2、使用servlet3.0(及以后版本都支持)完成文件上传

    (1)在servlet中声明注解:@MultipartConfig

    (2)声明part对象:Part part = request.getPart("file");  //获取这个文件对象

    (3)获取本地服务器的img路径:String filePath=request.getServletContext().getRealPath("/img/");

    (4)设置文件名称:String fileName = System.currenTimeMills()+request.getSession().getId();

    (5)写入文件:part.write(filePath+fileName+".jpg");

    3、多文件上传

    说明:多文件上传首先需要将利用h5中的特性,form表单添加属性mulitple

    (1)声明集合part对象

    Collection<Part> part = request.getPart();

    (2)进行遍历foreach遍历,写入part.write();

     4、使用Ajax文件上传

    $.ajax({
                       url:'http://localhost:8080/testUpload/test',      //请求上传服务器地址
                        type:"post",                         //请求方式,必须为post
                        cache:false,
                        data:new FormData($("form")[0]),              //请求参数,必须设置为二进制形式
                        processData:false,
                        contentType:false,
                        success:function(result){
                            alert("上传成功!")
                            $("img").slideToggle()
                        },
                        beforeSend:function(){
                            //让图片显示加载
                            $("img").slideToggle()
                        },error:function(){
                            alert("上传失败")
                        }
                        
                    })
                }

    5、文件下载

    (1)设置文件下载的格式:  response.setContentType("application/x-download");

    (2)设置请求头:  response.addHeader("Content-Disposition","attachment;filename="+name+".jpg");

    (3)创建文件对象:  File file = new File(request.getServletContext().getRealPath("/img/"+name+".jpg"));

    (4)创建文件输入流对象:  FileInputStream fis = new FileInputStream(file);    //将文件放进文件输入流

    (5)设置每秒下载速度:  byte[] b = new byte[1024];

    (6)int i=-1;

    (7)遍历文件流,进行写入到指定位置

    while((i=fis.read(b))>0){
      response.getOutputStream().write(b,0,i);      
    }
  • 相关阅读:
    Apache ActiveMQ消息中间件的基本使用
    struts2结合生成验证码
    Python中docstring文档的写法
    Nginx+uWSGI+Django原理
    Python垃圾回收机制详解
    Python数据库连接池实例——PooledDB
    构建高可用服务端
    Python使用multiprocessing实现一个最简单的分布式作业调度系统
    python3 分布式进程(跨机器)BaseManager(multiprocessing.managers)
    python BaseManager分布式学习
  • 原文地址:https://www.cnblogs.com/ByteBeat/p/11338193.html
Copyright © 2011-2022 走看看