ajax實例:實現文件下載和上傳

下載文件

$.ajax({
    type: "Get",
    headers: { 'Content-Type': 'application/octet-stream' },
    url: `${url}`,
}).then(result => {
    var fileName = "fileName.jpg";
    let blob = new Blob([result], { type: 'application/octet-stream' });
    if (typeof window.navigator.msSaveBlob !== 'undefined') {
        window.navigator.msSaveBlob(blob, fileName)
    } else {
        let URL = window.URL || window.webkitURL
        let objectUrl = URL.createObjectURL(blob)
        if (fileName) {
            var a = document.createElement('a')
            if (typeof a.download === 'undefined') {
                window.location = objectUrl
            } else {
                a.href = objectUrl
                a.download = fileName
                document.body.appendChild(a)
                a.click()
                a.remove()
            }
        } else {
            window.location = objectUrl
        }
    }
})

上傳文件

<form id="form" method="post" enctype="multipart/form-data">
    <input id="upload-btn" name="file"/>
</form>
var form_data = new FormData($('#form')[0]);

$.ajax({
    type: "POST",
    url: `${url}`,
    data: form_data,
    processData: false,
    contentType: false,
    success: function (result) {
        //TODO
    }
});

 

發佈了23 篇原創文章 · 獲贊 7 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章