简体   繁体   English

如何将 Blob 对象转换为文件并将其发送到服务器

[英]How can i convert Blob Object to a file and send it to the server

I want to convert a blob mp3 audio object in javascript to a file and send to the server.我想将 javascript 中的 blob mp3 音频对象转换为文件并发送到服务器。

So this is my code:所以这是我的代码:

function createDownloadLink(blob,encoding) {

    var url = URL.createObjectURL(blob);
    var au = document.createElement('audio');
    var li = document.createElement('li');
    var link = document.createElement('a');

    // Put in the server

    var token = $("#token").val();

    var formData = new FormData();
    

    formData.append("_token", token);
    formData.append('audio', blob);
    
    $.ajax('https://myip/audio', {
        method: "POST",
        data: formData,
        processData: false,
        contentType: false,
        success: function (data) {
            console.log(data);
        },
        error: function (data) {
            console.log(data);
        }
    });
}

The response is for the server is the following:服务器的响应如下:

{"_token":"3Qtbk53PLvzTzDBZrYwZY9WrHC7I6jmy9G6Aj6zw","audio":{}}

When i make console.log to the blob object appear this当我将 console.log 设置为 blob 对象时会出现这个

Blob {size: 32914, type: "audio/mpeg"}
size: 32914
type: "audio/mpeg"
__proto__: Blob
arrayBuffer: ƒ arrayBuffer()
size: (...)
slice: ƒ slice()
stream: ƒ stream()
text: ƒ text()
type: (...)
constructor: ƒ Blob()
Symbol(Symbol.toStringTag): "Blob"
get size: ƒ size()
get type: ƒ type()
__proto__: Object

Any ideas to solve this?有什么想法可以解决这个问题吗?

Following snippets converts a blob to file and appends it to the formdata以下代码段将blob转换为file并将其附加到 formdata

const blobFile = new File([blob], 'your_file_name');
formData.append("audio", blobFile);

However blob should work fine as well, as file is also a blob.但是blob应该可以正常工作,因为文件也是一个 blob。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM