【问题标题】:How to upload the file content that is inside a variable with jQuery?如何使用 jQuery 上传变量内的文件内容?
【发布时间】:2018-12-24 07:50:47
【问题描述】:

如何使用 ajax 发送文件内容“数据”? 如何设置该文件的名称?

我希望在没有 DOM“表单/输入”的情况下这样做

<script>

var file_to_upload = "hi I'm the content of a file";

$.ajax({
    url: 'php/upload.php',
    data: file_to_upload,
    cache: false,
    contentType: 'multipart/form-data',
    processData: false,
    type: 'POST',
    success: function(data){
        alert(data);
    }
});

<script>

【问题讨论】:

  • 我认为 jQuery 没有内置支持通过 ajax 发布文件。 fetch 确实如此(并且内置在现代浏览器中),因为body 可以是Blob,而您从input 元素上的FileList 获得的File 对象是Blob
  • 不,这不是我要问的
  • 请在发帖前花时间确保您的问题清晰完整。
  • 我做了,有什么不清楚的地方?我会澄清

标签: jquery ajax file-upload jquery-file-upload


【解决方案1】:

我认为 jQuery 没有内置支持通过 ajax 发布文件。 fetch 确实如此(并且内置于现代浏览器中),因为 body 可以是 BlobBufferSourceArrayBuffer 或类型化数组)。

您可以将 blob 或缓冲区作为请求的主体发送,或者如果您想在多部分表单上传中将其作为命名参数发送,您可以创建一个 FormData 实例并使用 Blob 作为调用append 时的值。比如:

// This is off the top of my head, not meant to be a perfect,
// all-singing, all-dancing example. You'll need to read the
// linked documentation and adjust as necessary.
var blob = new Blob([/*...file data...*/], {type: "appropriate/mimetype"});
var data = new FormData();
data.append("parameterName", blob);
fetch("php/upload.php", {
    method: "POST",
    body: data
})
.then(response => {
    if (!response.ok) {
        throw new Error("HTTP error " + response.status);
    }
    return response.text(); // or perhaps response.json()
})
.then(result => {
    // ...use the response
})
.catch(error => {
    // ...handle/report the error
});

/*...file data...*/ 可以是类型化数组、ArrayBuffer 等;详情请见the Blob constructor

或者,如果这是在 async function 内:

try {
    let blob = new Blob([/*...file data...*/], {type: "appropriate/mimetype"});
    let form = new FormData();
    data.append("parameterName", blob);
    let response = await fetch("php/upload.php", {
        method: "POST",
        body: data
    });
    if (!response.ok) {
        throw new Error("HTTP status " + response.status);
    }
    let result = await response.text(); // or perhaps response.json()
    })
    // ...use the response
} catch(error) {
    // ...handle/report the error
}

【讨论】:

    猜你喜欢
    • 2017-09-25
    • 2016-03-16
    • 1970-01-01
    • 2011-08-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-29
    • 2012-12-04
    相关资源
    最近更新 更多