简体   繁体   中英

sending local mp3 file to api server using jquery

I wish to use echoprint - http://echoprint.me/start - which allows me to send an mp3 file locally from my computer in a post request, and returns a json object including the song's details from their server.

I am attempting to make this post request using jquery in order to allow me retrieve the json object containing the song details, which will then allow me view this in my browser's console.

The echoprint website - http://developer.echonest.com/docs/v4/track.html - explains how to make this post request using curl. The following code works in the command line. This returns a json object, however this gets returned in the terminal.

curl -F "api_key=#############" -F "filetype=mp3" -F "track=@tambourineMan.mp3" "http://developer.echonest.com/api/v4/track/upload"

I have read the curl docs http://curl.haxx.se/docs/httpscripting.html#POST to try and understand where the correlation exists between the curl and jquery, but unfortunately I am having difficulties relating the two and understanding what -F means.

My aim is to make this post request using jquery so I can make the same request as outlined using curl above, and retrieve the json data in the browser's console.

From a previous question I asked on here I have tried to adopt the logic from that answer and used the following code, however this returns an error that the file cannot be encoded. I have tried it with and without the content type specified, but both methods fail.

   $.post("http://developer.echonest.com/api/v4/track/upload", {
              "api_key":"##################",
              "track":"@tambourineMan.mp3",
              "filetype":"mp3",
              "contentType:" "application/octet-stream"
          },
          function( data ) {
                  console.log(data)
          },
          "JSON" );

There are instructions here http://developer.echonest.com/docs/v4/track.html but they only explain how to do this using curl. If anyone could shed any light on this it would be greatly appreciated. Pardon my ignorance in advance.

cURL uses the @ prefix to mean "the contents of the named file", in your AJAX request you are sending @tambourineMan.mp3 as a literal string .

One easy to way to accomplish your task is to put a file input in your document and tell jQuery to use the data from that file:

var file = document.getElementById('myFileInput').files[0];
$.post("http://developer.echonest.com/api/v4/track/upload", {
    "api_key":"##################",
    "track":file,
    "filetype":"mp3",
    "contentType:" "application/octet-stream"
});

Take a look at the FileReader API and at this article about sending and receiving binary data in a XMLHttpRequest

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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