1. 程式人生 > >大文件上傳解決方案

大文件上傳解決方案

eset rac get url eal spa transfer proc []

代碼: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();
            }

        }

    }

大文件上傳解決方案