Skip to main content
 首页 » 编程设计

jQuery 上传到公共(public) S3 存储桶给出 ------WebKitFormBoundary

2026年09月08日2pengyingh

我有一个网页,它获取公共(public) S3 存储桶名称和用于上传的唯一文件名。我正在使用 jQuery 从 javascript 直接进行上传。文件上传,但多部分信息被添加到文件中,从而损坏了文件。

我尝试了不同的 jQuery ajax 参数,例如将 contentType 设置为“image/jpeg”并尝试使用 PUSH 而不是 PUT。我什至尝试手动将文件添加到新的 FormData() 对象,如下所示。

我不明白如何编写一个简单的 CURL 命令,该命令可以正常工作,但我无法使用 jQuery 提交 HTML 表单。我觉得 jQuery 被丢弃了,并且没有正确地放在 S3 存储桶一侧。

HTML

<form id="upload-image-form" className="clearfix" method="PUT" enctype="multipart/form-data"> 
<input id="product-images-add-btn" name="product-images-add-btn" type="file" onChange={this.startImageUpload} /> 
</form> 

Javascript

$("#upload-image-form").submit(function(e) 
{ 
    e.preventDefault(); 
 
    var formURL = $(this).attr('action'); 
    //var formData = new FormData($("#product-images-add-btn")[0]);   
    var formData = new FormData(); 
    formData.append("file", $("#product-images-add-btn")[0].files[0]);           
 
    $.ajax({ 
        url:         formURL, 
        type:        "PUT", 
        data:        formData, 
        crossDomain: true, 
        contentType: false, 
        processData: false, 
        success:     function(data, textStatus, jqXHR) 
        { 
            console.log('Successful image upload!'); 
            //tempThis.finishImageS3Upload(); 
        }, 
        error: function(jqXHR, textStatus, errorThrown) 
        { 
            console.error("Image upload error."); 
        } 
    }); 
    return false; 
}); 
 
 
 
startImageUpload: function(){ 
    var input = $("#product-images-add-btn"); 
    var files = input[0].files; 
    var fileTypes = [".gif",".jpg", ".png"]; 
 
    console.log("--- DEBUG. Number of files: "+files.length); 
 
    var tempThis = this; 
 
    if(files.length > 0) 
    { 
        var ext = input.val().match(/\.([^\.]+)$/)[0]; 
 
        if(fileTypes.indexOf(ext) > -1) 
        { 
            var file = files[0]; 
            var assetData = { 
                "filename":    file.name, 
                "filesize":    file.size, 
                "type":        "IMAGE", 
                "format":      file.type 
            }; 
 
 
            $.ajax({ 
                url: "/getImageUploadS3Info", 
                cache: false, 
                contentType: 'application/json', 
                crossDomain: true, 
                data: assetData, 
                success: function(s3Info){ 
                    s3Info.filename = file.name; 
                    tempThis.uploadImageS3(s3Info); 
                }, 
                error: function(a, x, e){ 
                    console.error("getS3InfoForUpload() ajax error."); 
                } 
            }); 
 
        } 
        else 
            console.warn("--- DEBUG. File extension "+ext+" not allowed."); 
    } 
    else 
        console.log("--- DEBUG. No files to upload."); 
} 
 
 
uploadImageS3: function(s3Info){ 
    if(s3Info.hasOwnProperty("assetId")) 
    {         
        $("#upload-image-form").attr('action', s3Info.httpUrl) 
            .data('assetId', s3Info.assetId); 
 
        console.log("--- DEBUG: submitting form."); 
        $("#upload-image-form").submit(); 
    } 
    else 
        console.warn("--- ERROR: the response for getImageUploadS3Info wasn't correct."); 
 
} 

S3 文件

------WebKitFormBoundaryluTBbSMgcV0BEJcC 
Content-Disposition: form-data; name="file"; filename="NewGrass.jpg" 
Content-Type: image/jpeg 
 
<image byte info stuff> 

请您参考如下方法:

在 Firefox(最新)、Chrome(最新)和 IE10、IE11 和 Edge 中进行测试后,该解决方案确实非常有效!这里不需要 jquery 的 ajax 方法的开销。浏览器(即 IE)确实获取了 XMLHttpRequest 对象。这将完成 S3 的工作,但我仍在研究使用 jQuery 的 $.ajax() 方法的解决方案,以实现 100% 跨浏览器兼容性(但我们不支持 IE9,因此我们不需要) :

function sendToServer (imgFile) { 
    var dateTime = new Date().getTime(),//used for file name 
        url = '//bucketUrl?fileName=image' + dateTime + '.png', 
        xhr = new XMLHttpRequest(), 
        fd = new FormData(), 
        fileBlob = dataURItoBlob(img); 
 
    fd.append('file', fileBlob); 
 
    xhr.open('POST', url, true); 
 
    xhr.onreadystatechange = function() { 
        if (xhr.readyState == 4 && xhr.status == 200) { 
            // Every thing ok, file uploaded 
            console.log(xhr.responseText); // handle response. 
        } 
    }; 
 
    xhr.send(fd); 
} 
 
function dataURItoBlob(dataURI) { 
    // convert base64/URLEncoded data component to raw binary data held in a string 
    var byteString, 
        byteStringLength, 
        mimeString, 
        ia, 
        i = 0; 
 
    if (dataURI.split(',')[0].indexOf('base64') >= 0) { 
        byteString = atob(dataURI.split(',')[1]); 
    } 
    else { 
        byteString = unescape(dataURI.split(',')[1]); 
    } 
 
    byteStringLength = byteString.length 
 
    // separate out the mime component 
    mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0]; 
 
    // write the bytes of the string to a typed array 
    ia = new Uint8Array(byteStringLength); 
 
    for(; i < byteStringLength; i++) { 
        ia[i] = byteString.charCodeAt(i); 
    } 
 
    return new Blob([ia], { 
        type: mimeString 
    }); 
} 

您似乎忘记在发送前编码为 blob。这可能就是您所需要的。获取该decodeURItoBlob 函数并查看该逻辑是否适用于您的jquery ajax 方法...否则,您可以使用javascript xhr 来发送它。