• 大文件上传解决方案


    代码:JavaScript

      1 /**
      2  * 骆武辉
      3  */
      4     var videoUrl;
      5 $(function() {
      6             var fileSeed = new Array();// 保存分片表单
      7             var loser= new Array();// 保存上传失败文件
      8             var Interval;// 重复事件监听参数
      9             var uploadState=true;// 分片表单使用状态
     10             var fileName;
     11             var sizeNum;
     12         
     13             $("#upinput").change(function() {
     14                 $(".progress").show();
     15                 console.info(this);
     16                 // 获取文件流
     17                 var file1 = this.files[0];
     18                 if(file1.type=="video/mp4"){
     19                     
     20             
     21                 console.info(file1);
     22                 // 获取文件名
     23                  fileName = file1.name;
     24                 
     25                 // 获取文件大小
     26               sizeNum = file1.size;
     27                 // console.info(sizeNum);
     28                 // console.info(postfix);
     29                 // 后缀判断
     30                 var shardSize = 4*1024 * 1024; // 以1MB为一个分片
     31                 var shardCount = Math.ceil(sizeNum / shardSize); // 总片数
     32                 // console.info(shardCount);
     33                 // 文件切片
     34                 var index = 0;
     35                 Interval = setInterval(function() {
     36                     // console.info("正在分片..." + index);
     37                     // 计算每一片的起始与结束位置
     38                     var start = index * shardSize,
     39                         end = Math.min(sizeNum, start + shardSize);
     40                     // 构造一个表单,FormData是HTML5新增的
     41                     var form = new FormData();
     42                     form.append("data", file1.slice(start, end)); // slice方法用于切出文件的一部分
     43                     form.append("name", index+"_"+fileName );
     44                     // 保存到数组
     45                     fileSeed[index] = form;
     46                     progress(shardCount, index);
     47                     // console.log("表单" + fileSeed[index]);
     48                     index++;
     49                     console.log(index == shardCount);
     50                     if(index == shardCount) {
     51                         // 停止重复事件
     52                         clearInterval(Interval);
     53                         progress(shardCount, shardCount);
     54                     }
     55                 }, 5);
     56                 }else $(this).attr("value",null);
     57             });
     58 
     59             function progress(shardCount, i) {
     60                 var num = i / shardCount * 100;
     61                 // 修改长度
     62                 $(".progress-seed").css("width", num + "%");
     63             }
     64             
     65             
     66             function progress(shardCount, i) {
     67                 var num = i / shardCount * 100;
     68                 console.info(num);
     69                 // 修改长度
     70                 $(".progress-seed").css("width", num + "%");
     71             }
     72             
     73             function combineVoid(index) {// 合并请求
     74                 // Ajax提交
     75                  $.ajax({
     76                     url: "/video/combineVoid",
     77                     type: "POST", 
     78                     scriptCharset: 'utf-8',
     79                     data:{
     80                         "fileName":fileName,
     81                         "fileSzie":sizeNum,
     82                         "index":index
     83                     },
     84                     success: function(data) {
     85                     // alert(data);
     86                         // 成功后的事件
     87                         if(data!="false")
     88                         videoUrl=data;
     89                         else
     90                             alert("验证失败");
     91                     }
     92                 }); 
     93             }
     94             function uploadAjax(filePiece){
     95                 uploadState=false;            
     96                 // Ajax提交
     97                  $.ajax({
     98                     url: "/video/upload",
     99                     type: "POST",
    100                      resetFomr: true,                     
    101                     data:filePiece ,
    102                     async: false, // 同步减请浏览器负担
    103                     processData: false, // jquery不要对form进行处理
    104                     contentType: false, // 指定为false才能形成正确的Content-Type
    105                     success: function(data) {
    106                         // 成功后的事件
    107                         if (data=="false") {// 上传失败标记
    108                             console.info("上传期间出现错误");    
    109                             loser[loser.length]=filePiece;
    110                         }
    111                         uploadState=true;
    112                     }
    113                 }); 
    114             }
    115             
    116             // 监听ctlBtn
    117             $("#ctlBtn").click(function() {
    118                 if(fileName!=null && fileName!=""){
    119                     
    120                 
    121                 var index=0;
    122                 $(".right840").empty();
    123                 $(".right840").load("/html/user_upload2.html");            
    124                 // 定时执行
    125                 Interval= setInterval(function() {                
    126                     if(uploadState){
    127                         // 加入上传列队
    128                         uploadAjax(fileSeed[index]);
    129                         index++;
    130                     }
    131                     if(index==fileSeed.length){
    132                         clearInterval(Interval);
    133                         // 校验提醒
    134                         combineVoid(index);
    135                         alert("上传完成");
    136                     }
    137                 },50);
    138                 }
    139             });
    140         });

    代码:java

    public static boolean uploadFile(MultipartFile data, String name) {
            // TODO Auto-generated method stub
            boolean falg = false;
            // 设置保存位置
            String realPath = "F:\cache";
            // 创建文件
            File targetFile = new File(realPath, name);
            if (!targetFile.exists()) {
                targetFile.mkdirs();
            }
            try {
                // 保存文件流
                data.transferTo(targetFile);
                falg = true;
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return falg;
        }
    /**
         * 文件合并工具
         * @param fileName 
         * @param index 
         * @return 
         */
        public static String fileCombinePlant(String fileName, Integer index, Integer fileSzie) {
            String result;
            // TODO Auto-generated method stub
            int byteSzie = 100 * 1024;
            int nextInt = new Random().nextInt(10000);
            OutputStream out = null;
            BufferedOutputStream outputStream = null;
            List<File> files = new ArrayList<>();
            try {
                result = nextInt + fileName;
    
                // 创建流对象
                out = new FileOutputStream("F:\vide\vod1\" + result);
                outputStream = new BufferedOutputStream(out);
                // 匹配文件
                for (int i = 0; i < index; i++) {
    
                    // 创建文件对象
                    File file = new File("F:\cache\" + i + "_" + fileName);
                    files.add(file);
                    InputStream intpu = new FileInputStream(file);
                    // 读取文件到流
                    byte[] b = new byte[byteSzie];
                    int read = 0;
                    try {
                        // 读取数据
                        while ((read = intpu.read(b, 0, b.length)) > 0) {
                            // 输出数据
                            outputStream.write(b, 0, read);
                        }
                        // 关闭读入流
                        intpu.close();
                    } catch (IOException e) {
                        result = "false";
                        System.out.println("FileUtil-->fileCombinePlant读取流错误");
                        e.printStackTrace();
                    }
                }
    
            } catch (FileNotFoundException e) {
                result = "false";
                // TODO Auto-generated catch block
                System.out.println("FileUtil-->fileCombinePlant输出流错误");
                e.printStackTrace();
            } finally {
                try {
                    outputStream.flush();
                    outputStream.close();
                    out.flush();
                    out.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
    
            }
            // 删除缓存文件
            removeFile(files);
            return result;
        }
    
        /** 删除文件
         * @param files
         */
        private static void removeFile(List<File> files) {
            // 遍历集合
            for (File file : files) {
    
                // 判断文件是否存在
                if (file.exists()) {
                    // 删除文件
                    file.delete();
                }
    
            }
    
        }
  • 相关阅读:
    UIApplicationMain函数做了什么
    Navigation Bar的简单设置
    Xcode调试 之 内存泄露 .
    ASIHTTPRequest类库简介和使用说明
    IOS开源项目汇总
    列表框的左右移动,单个,多个,全部
    window.showModalDialog以及window.open用法简介
    URL编码方法比较 Encode,Javascript,escape,encodeURI,encodeURIComponent,UTF8
    实现repeater控件多列显示 简单方法(用CSS float属性)
    如何部署强命名程序集(Strong Name Assembly)和GAC
  • 原文地址:https://www.cnblogs.com/sylwh/p/8004767.html
Copyright © 2020-2023  润新知