2015-05-14 131 views
2

我已經創造了2個XML文件這種方式使用JSZIP庫文件,即一個zip文件,

jszip.js

jszip-load.js

jszip-inflate.js

jszip -deflate.js

var zip = new JSZip(); 
zip.file("hi.xml", "<?xml version="1.0"?><root/></root></xml>"); 
zip.file("hello.xml", "<?xml version="1.0"?><pest/></pest></xml>"); 
//var content = zip.generate({ compression: "DEFLATE" }); 
var content=zip.generate({base64: true, binary: true, compression: "DEFLATE" }); 

這荏苒部分是成功的,因爲我能夠得到downloads.z​​ip 2上述文件hi.xml &的hello.xml在我的下載文件夾,如果我添加此代碼,

location.href="data:application/zip;base64,"+content; 

但我通過AJAX不使用HTML表單上載該壓縮文件時,服務器遇到了問題。這是我在做的代碼,

var oBlob = new (window.BlobBuilder || window.WebKitBlobBuilder || 
       window.MozBlobBuilder || window.MSBlobBuilder)(); 

     var raw = atob(content); //decode the base64 string 
     var rawLength = raw.length; 
     var uInt8Array = new Uint8Array(rawLength); 
     for (var i = 0; i < rawLength; ++i) { //convert to uInt8Array 
      uInt8Array[i] = raw.charCodeAt(i); 
     } 

     oBlob.append(uInt8Array.buffer); //append it to blobbuilder 
     oMyForm.append(content, oBlob.getBlob("application/zip")); //because you create a zip file, so get the zip type 

     //send it 
     $.ajax({ 
     type: 'POST', 
     url: 'requestURL',//java spring servlet URL 
     async: false, 
     data: { 
      name:'user', 
     files:oMyForm 
     }, 
     success: function(msg){ 
     }, 
     error : function(jqXHR, textStatus, errorThrown) { 
      if(typeof jqXHR == 'object'){ 
       if(typeof jqXHR.responseText != 'undefined'){ 
        if(jqXHR.responseText == 'success'){       

        } 
       } 
      } 
     } 

    }); 

有人能幫我解決這個問題嗎?

我也做過這樣,

var oBlob = new (window.BlobBuilder || window.WebKitBlobBuilder || 
       window.MozBlobBuilder || window.MSBlobBuilder)(); 

    var raw = atob(content); //decode the base64 string 
    var rawLength = raw.length; 
    var uInt8Array = new Uint8Array(rawLength); 
    for (var i = 0; i < rawLength; ++i) { //convert to uInt8Array 
     uInt8Array[i] = raw.charCodeAt(i); 
    } 

    oBlob.append(uInt8Array.buffer); //append it to blobbuilder 
    oMyForm.append(content, oBlob.getBlob("application/zip")); //because you create a zip file, so get the zip type 

    //send it 
    var oReq = new XMLHttpRequest(); 
    oReq.open("POST", 'requestURL'); 
    oReq.send(oMyForm); 

是什麼,我在這裏失蹤?爲什麼zip文件沒有發佈到服務器?

有人能幫助我嗎?

回答

2

在別的之前,一定要使用最新的JSZip版本(例如jszip-inflate.js不再存在)。

靈感來自How can javascript upload a blob?

var zip = new JSZip(); 
zip.file("hello.xml", "..."); 
var content = zip.generate({ 
    type: "blob", 
    compression: "DEFLATE" 
}); 

var fd = new FormData(); 
fd.append('name', 'user'); 
fd.append('zip', content); 

$.ajax({ 
    type: 'POST', 
    url: 'requestURL', 
    data: fd, 
    processData: false, 
    contentType: false 
}).done(function(data) { 
    console.log(data); 
}); 
相關問題