I'm trying to upload a file to Amazon AWS from Javascript with a signed URL obtained from a django api where I sign it with the help of Boto. This is my line in python:
url = conn.generate_url(300, 'PUT', settings.AWS_VIDEO_BUCKET, key, headers={'Content-Length': '19448423'}, force_http = True )
Using the URL generated from this, I can post to S3 with CURL like so:
curl -v --request PUT --upload-file video.mp4 "http://some_signed_url"
What does not work though, is using this URL to PUT a file to Amazon AWS via Javascript. Debugging with a proxy reveals a broken pipe error, while CURL would give me the regular Amazon Access Denied XML if something went wrong. This is my javascript code (file is a JS File object):
var file = e.originalEvent.dataTransfer.files[0];
var fd = new FormData();
fd.append( 'file', file );
$.ajax({
url: 'signed_url',
data: fd,
processData: false,
contentType: false,
cache: false,
type: 'PUT',
success: function(data){
console.log("success");
},
error: function(data){
console.log(data.responseText);
}
});
Any ideas where to go from here? Maybe I'm not including all the required headers in the signing process, or FormData is not the right way to go.
Related
I am trying to upload files using pre-signed url to s3 bucket. I am getting the pre-signed url by hitting a rest endpoint, which returns a json with the required details.
Now, I have to take this json and get the input file from user, to upload the file.
Here is the code, I have written in coffeescript. I am taking an input file obj from user and storing in file object and then calling the pre-signed api to get the json.
uploadFile: (e) =>
files_container = e.target.form.elements[0].files
if files_container.length > 0
#file_obj = files_container[0]
console.log(#file_obj)
result = ""
$.ajax
type: 'GET'
url: '/api/upload/get_lead_upload_url'
dataType: "json"
success: (response) ->
console.log(response)
Below, I have to write this python code in coffeescript to upload the file.
with open(object_name, 'rb') as f:
files = {'file': (object_name, f)}
http_response = requests.post(response['url'], data=response['fields'], files=files)
# If successful, returns HTTP status code 204
Below is the part, where I am going wrong while creating the payload like the python code.
formdata = new FormData
formdata = response.fields
formdata['file']= {#file_obj['name'], #file_obj}
console.log(formdata)
The post request is giving me 403 forbidden error.
$.ajax
type:'POST'
dataType: "jsonp"
url: response.url
headers: {'Access-Control-Allow-Origin': '*'}
data: formdata
success: (uploadResponse) ->
console.log(uploadResponse)
error: (uploadResponse) ->
console.log('error')
console.log(uploadResponse)
error: (response) ->
console.log('error')
I have array of video files. i tried to upload. in below code console gives result empty object. How to select video file and upload. is it possible??
var pictureInput=['hp.mp4'];
var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput[0]);
console.log(myFormData)
$.ajax({
url: 'uploadurl',
type: 'POST',
processData: false,
contentType: false,
dataType : 'json',
data: myFormData
});
For security reasons, it is not possible to read or upload files by name from a script. The user must either explicitly select the files from a dialog, or drag-and-drop them to the page. (If it were allowed, pages would be able to read and transmit any file on your system simply by knowing the name, which is not a good thing!)
You can find out more about how to let users specify files on the web here: https://developer.mozilla.org/en/docs/Using_files_from_web_applications
Use file object instead of file name only.
Previously i made successful this with Google App Engine (Java) and Angular 1.5
Look this accepted answer too. jQuery equivalent to XMLHttpRequest's upload?
var formData = new FormData();
formData.append('pictureFile',FILE_OBJECTS[0]);
$.ajax({
url: "YOUR_URL",
type: "POST",
data: formData,
cache: false,
contentType: false,
processData: false,
xhr: function() { // Custom XMLHttpRequest
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
}).success(function(data) {
console.log("Success")
}).error(function(data) {
console.log("Error")
});
I'm getting a Error :
"POST {URL} 415 (Unsupported Media Type)" error
And cannot figure out why it's happening.
I'm trying to upload an excel file in JQuery using FormData.
Here is the code:
var formdata = new FormData();
var file = input.get(0).files[0];
formdata.append('content', file);
var url = "/Phrase/Import/" + $('.exportPanel #Language').val()
var ajax = $.ajax({
url: url,
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function (data, textStatus, jqXHR) {
//Do something.
},
error: function (jqXHR, textStatus, errorThrown) {
//Do something.
}
});
Here is the controller code:
[Route("Import/{languageID}")]
[HttpPost]
public void ImportPhrases([FromUri]int languageID, [FromBody]Stream content)
{
_service.ImportPhrases(content, languageID);
}
I noticed that, according to Fiddler, the content type of the request is different to that of the response (not sure if this makes a difference?).
Request: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
Response: application/json; charset=utf-8
The JQuery above is being used in a different part of the system, but uses WCF instead of Web API (am in the process of changing from WCF to MVC/Web API), again I'm not sure if this makes a difference?
Can anyone tell me what I'm doing wrong please?
Many thanks.
415 Unsupported Media Type
The request entity has a media type which the server or resource does not support. For example, the client uploads an image as image/svg+xml, but the server requires that images use a different format.
contentType does matter - it tells the server what you are uploading. In this instance, you have set the value to false. The server cannot recognise this, so it returns false. If you do not need a specific content type, you should remove the contentType line to allow the jQuery default to kick in.
I am trying to use BusinessObject RESTful API to download a generated (pdf or xls) document.
I am using the following request:
$.ajax({
url: server + "/biprws/raylight/v1/documents/" + documentId,
type: "GET",
contentType: "application/xml",
dataType: "text",
headers: {"X-SAP-LogonToken": token, "Accept": "application/pdf" },
success: function(mypdf) {
// some content to execute
}
});
I receive this data as a response:
%PDF-1.7
%äãÏÒ
5 0 obj
<</Length 6 0 R/Filter/FlateDecode>>
//data
//data
//data
%%EOF
I first assumed that it was a base64 content, so in order to allow the users to download the file, I added these lines in the success function:
var uriContent = "data:application/pdf; base64," + encodeURIComponent(mypdf);
var newWindow=window.open(uriContent, 'generated');
But all I have is an ERR_INVALID_URL, or a failure while opening the generated file when I remove "base64" from the uriContent.
Does anyone have any idea how I could use data response? I went here but it wasn't helful.
Thank you!
. bjorge .
Nothing much can be done from client-side i.e. JavaScript.
The server side coding has to be changed so that a url link is generated (pointing to the pdf file) and sent as part of the response. The user can download the pdf from the url link.
You cannot create file using javascript, JavaScript doesn't have access to writing files as this would be a huge security risk to say the least.
To achieve your functionality, you can implement click event which target to your required file and it will ask about save that file to user.
I am having trouble with the google app engine blob store. I am running in the development environment (ie local on my machine.)
Heres what i am doing...
once the form pops up i call into a servlet to generate the URL like this
String url = blobstoreService.createUploadUrl("test/joi");
once i have that i save it in my java scrip and then once the user submits the form i am doing this
$.ajax({ url: self.url,
type: "POST",
//crossDomain: true,
dataType: "jsonp",
//dataType: "multipart/form-data",
success:
function(response, textStatus, jqXHR)
{
alert("saved.");
}
});
}
however, when i do that i get the following exception
GET 405 (HTTP method GET is not supported by this URL) jquery.js:4
i am really struggling with this and any help would be greatly appreciated!
Apart from any other issues, the blobstore expects file uploads in multipart form format; you're attempting to post to it using jquery. If you want to do the post in javascript, you will need to format the body of the POST request appropriately.