How to upload file to aws s3 using xmlhttprequest - javascript

How can I upload file to s3 using xmlhttprequest. I tried following way but I got error like
'Anonymous access is forbidden for this operation'.
Here is my code:
const xhr = new XMLHttpRequest();
xhr.open('PUT', "https://region.amazonaws.com/bucket-name/");
xhr.setRequestHeader('X-Amz-ACL', 'public-read');
xhr.setRequestHeader('Content-Type', 'image/png');
xhr.send({
file: file,
type: 'image/png',
name: "myfile_9898_0",
acl: 'public-read',
AWSAccessKeyId: 'aws key',
AWSSecreKeyId: 'scret_key'
});
Is there anything wrong with this code?
Can anyone help me?

you spelled SecretKey wrong.
however, anyone viewing this page (assuming it's in a html page) can steal your credentials! it's a Really Bad Idea to put secretKey anywhere - you're better to generate a 'pre-signed key' on the server with your secret. You'll also need CORS set up on your server to allow the cross-post.

Related

javascript post blob to back-end java

i recorded a video using javascript (with recordRTC) , now i have it as a blob :
mediaRecorder.onstop = (ev)=>{
let blob = new Blob(chunks, { 'type' : 'video/mp4;' });
chunks = [];
let videoURL = window.URL.createObjectURL(blob);
vidSave.src = videoURL;
var file = new File([blob], 'video.mp4', {
type: 'video/mp4'
});
invokeSaveAsDialog(file);
// my attempt to send this blod //
let req = new XMLHttpRequest();
let formData = new FormData();
formData.append("video", blob);
req.open("POST", 'http://localhost:8081/avi/recieveAndParseVideo');
req.send(formData);
//
}
now i am trying to send it to my back-end application i dont know how , i created a java method:
#PostMapping("/recieveAndParseVideo")
public String uploadingPost(#RequestBody MultipartFile uploadingFile) throws IllegalStateException, IOException {
System.out.println(uploadingFile);
File file = new File("C://" + uploadingFile.getOriginalFilename());
uploadingFile.transferTo(file);
return file.getName();
}
when i execute the top javascript method it throws this exception:
Access to XMLHttpRequest at 'http://localhost:8081/avi/recieveAndParseVideo' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
guys i dont even know if this is the right way to send a post via javascript , and is my java code correct to receive the file?
please help
Welcome to the terrible and wonderful world of CORS. Cross-Origin Resource Sharing is what keeps you and me safe while we're browsing the Internet. Without it, websites could download and perform any code or content they wanted.
Imagine a website, foo.example was compromised. Someone found a way to make it download malicious code from their own website, bar.example. Without CORS policies, your browser would gladly run that code! With CORS, your browser says 'Hey wait a second, I'm at foo.example, why would I run code from another website?'
For local testing, your best solution is to install and configure a CORS plugin to your browser. An example for FireFox is CORS Everywhere, found here. This will let you access resources at localhost:8081 from localhost:4200.
For production, your server will need to send the appropriate response headers to your website, e.g. Access-Control-Allow-Origin: yourWebsite.example
More information about why and how CORS works

static file append in form data using angular 7 to post api http

I am trying to attach a file in formData , attaching file by uploading input type=file is working fine
But in my scenario I am having static file in assets folder so whenever Im trying to post api formData should have file: attachment in order to get access. I am trying on this more than a day still I couldn’t fix this issue.Please someone assist on this.Thanks in advance
let formData = new FormData();
formData.append('file','../../../../../assets/file.txt');
this.http.post(this.parameter, formData).subscribe(event => {
});
this returns null in formData and seems no attachment happens with this
and another way,
var request = new XMLHttpRequest();
request.open('POST', '../../../../../assets/file.txt', true);
request.send(formData);
this returns 404 not found even though path is correct.

Google Drive API V3 Javascript - Create File with Content

This question has been asked before, but the answer was using API V2. The google documentation does not clarify how to create a file with its content using javascript client code. I tried using the code listed under Node, however, it only creates the file, it does not insert any content. Here is my code:
let fileMetadata = {
'name': name,
parents: [parentId]
};
let media = {
mimeType: 'text/plain',
body: 'content inside file'
};
gapi.client.drive.files.create({
resource: fileMetadata,
media,
fields: 'id'
})
.then(response => {
console.log('response: ', response);
})
.catch(() => {
console.log('something is wrong');
});
Can someone help me insert content into files please?
How about this sample script? In my environment, although gapi.client.drive.files.create() can create an empty file on Google Drive, it cannot directly upload files including contents. I think that this might not be able to upload files and metadata with the multipart/related, although this might be resolved by the future update. So now, as one of workarounds, I use XMLHttpRequest.
Before you use this sample script, please confirm the following points.
In your situation, you have already been able to create files using gapi. In my script, the access token is retrieved using gapi.
When you use this script, please set fileContent and metadata.
Sample script :
In this sample script, a text file including contents is created under a folder.
var fileContent = 'sample text'; // As a sample, upload a text file.
var file = new Blob([fileContent], {type: 'text/plain'});
var metadata = {
'name': 'sampleName', // Filename at Google Drive
'mimeType': 'text/plain', // mimeType at Google Drive
'parents': ['### folder ID ###'], // Folder ID at Google Drive
};
var accessToken = gapi.auth.getToken().access_token; // Here gapi is used for retrieving the access token.
var form = new FormData();
form.append('metadata', new Blob([JSON.stringify(metadata)], {type: 'application/json'}));
form.append('file', file);
var xhr = new XMLHttpRequest();
xhr.open('post', 'https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart&fields=id');
xhr.setRequestHeader('Authorization', 'Bearer ' + accessToken);
xhr.responseType = 'json';
xhr.onload = () => {
console.log(xhr.response.id); // Retrieve uploaded file ID.
};
xhr.send(form);
Request body :
In this script, form is as follows. This is sent to Google Drive using the create method of Drive API.
------WebKitFormBoundaryxX0XmxgooMjdUECR
Content-Disposition: form-data; name="metadata"; filename="blob"
Content-Type: application/json
{"name":"sampleName","mimeType":"text/plain","parents":["#####"]}
------WebKitFormBoundaryxX0XmxgooMjdUECR
Content-Disposition: form-data; name="file"; filename="blob"
Content-Type: text/plain
sample text
------WebKitFormBoundaryxX0XmxgooMjdUECR--
In my environment, I confirmed that this works fine. But if this didn't work in your environment, I'm sorry.

Webcam js upload image to Amazon S3

I'm trying to upload an image taken with
Webcam js
directly to Amazon S3
var dataUri = Webcam.snap();
var raw = window.atob(dataUri.replace(/^data\:image\/\w+\;base64\,/, ''));
and after I get the policy (which is correct) I do this
$.ajax({
type: 'POST',
url: amazonUploadUrl,
data: {
file: raw,
contentType: "image/jpeg",
key: key,
AWSAccessKeyId: awsAccessKey,
acl: "public-read",
policy: policy,
signature: signature,
name: "",
Filename: filename
},
dataType: "",
success: function (r1) {
}
});
I've tried sending the encoded image, the decoded image, I've tried modifying the headers. All I keep getting is this
XMLHttpRequest cannot load 'amazon s3 bucket url'. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'my local domain' is therefore not allowed access.
I've added the CORS info on the Amazon bucket.
I'm already uploading images to that bucket using plupload.
I've also uploaded images from a standard without using ajax.
I just can't seem to get this to work.
Any ideas?
Thanks
PS: I've also tried using
jquery webcam plugin
With the same result
You'll need to use the javascript FormData object and native XMLHttpRequest methods to post the data directly to s3. I've tried to do the exact same thing this morning with jQuery and ran into that error message, but native javascript APIs work.
I have a feeling jQuery isn't using CORS by default or is sending across a the wrong header somewhere.
This answer shows how to convert to a format S3 can understand, which may not be necessary in your case.
This should get you started on the form data part:
var fd = new FormData();
fd.append("contentType", "image/jpeg");
fd.append("key", key);
fd.append("AWSAccessKeyId", awsAccessKey);
fd.append("acl", "public-read");
fd.append("policy", policy);
fd.append("signature", signature);
fd.append('filename', "");
fd.append('file', raw);
var xhr = new XMLHttpRequest();
xhr.open('POST', amazonUploadUrl);
xhr.addEventListener('load', function(e) {
console.log('uploaded!', e) // Successful upload!
});
// Optionally bind to other xhr events, like error, progress, or abort.
// Using native XHR2 is nice because the progress event works and you
// can tack on upload progress counters.
xhr.send(fd);

How to create an in memory file and upload to server using client side javascript?

I have a test suite written in JavaScript running in a browser that runs on an embedded system. The test suite collects a lot of data and I want to push that to the server. I could use a simple HttpRequest, post-method, but that would require a lot of character escaping to send the content. It would much simpler to upload it to the server as a file using http-file-upload.
Is there a way to create an in memory file and use http-file-upload to push it to a server, using client-side JavaScript?
Since the browser of the embedded system is Ekioh and the system itself is a minimal one, technologies such as flash, JavaApplet, SilverLight are not available. Only pure HTML5 and JavaScript are available.
I think a post would be the better way to do this. Dealing with escaped data is a much easier, more established problem then in-memory files and pushing files to the server with client side javascript. Moreover, escaping data is done for a reason. What you're trying to do is going to welcome a lot of security vulnerabilities.
Try doing something like this.
Snippet taken from Write javascript output to file on server
var data = "...";// this is your data that you want to pass to the server (could be json)
//next you would initiate a XMLHTTPRequest as following (could be more advanced):
var url = "get_data.php";//your url to the server side file that will receive the data.
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);//check if the data was revived successfully.
}
}
http.send(data);
This worked for me. The key part is to create a file and blob. I use angular JS to do the actual http call. However, once you have a file in memory, it shouldn't be too hard to send the data using your http client.
Note: I do the http call to https://httpbin.org/post. This echoes what the server received/parsed, which is useful while iterating to figure your problem out.
function multiPartPost(bodyObj) {
const url = 'https://httpbin.org/post';
const bodyJson = JSON.stringify(bodyObj);
const blob = new Blob([bodyJson], {
type: 'application/json;charset=UTF-8'
});
const fileName = 'jsonAttrs';
const file = new File([blob], fileName, {type: "text/json;charset=utf-8"});
const formData = new FormData();
formData.append(fileName, file);
return this.$http.post(url, formData, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
});
}

Categories

Resources