I'm trying to create a function that adds a new file into an S3 bucket in AWS. The function works in NodeJS.
const AWS = require('aws-sdk');
AWS.config.update({region: 'us-east-2'});
s3 = new AWS.S3({apiVersion: '2006-03-01'});
// call S3 to retrieve upload file to specified bucket
const file = "file.png";
const uploadParams = {Bucket: "uploads", Key: '', Body: ''};
const fs = require('fs');
const fileStream = fs.createReadStream(file);
fileStream.on('error', function(err) {
console.log('File Error', err);
});
uploadParams.Body = fileStream;
const path = require('path');
uploadParams.Key = path.basename(file);
s3.upload (uploadParams, function (err, data) {
if (err) {
console.log("Error", err);
} if (data) {
console.log("Upload Success", data.Location);
}
});
What I'm trying to do now is take this code and make it execute when a file is uploaded in HTML. I have a simple HTML script where users can upload files and I want the above code to execute when the submit button is pressed.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<form action="javascript:loadAPI(document.getElementByID('fileUpload'))">
<label>Upload a file to AWS S3</label>
<input type="file" id="fileUpload" name="filename">
<input type="submit">
</form>
<script type="text/javascript" src="apiFunction.js">
</script>
</body>
</html>
The problem is that if I put the node function within loadAPI, I get the following error.
Uncaught ReferenceError: require is not defined
Does anyone know how I can utilize this function from HTML?
CodePudding user response:
Uncaught ReferenceError: require is not defined
You are getting this error because require
function is the primary importing function used in CommonJS. AWS SDK is not meant for browser-side
usage. Using it on client-application will also require the HTML file to use AWS credentials and potentially expose them over the public internet which could be a security risk.
A better way of tackling your requirement of uploading files to S3 is the use of S3 pre-signed URLs. You can use this AWS guide as a starting point and then check out this blog after to get an idea on how to implement it on client-side apps.
CodePudding user response:
I'm not too sure how AWS works, but the if the function is stored on a web adress, you can make a request to that. For example, if the function is stored on https://www.aws/youproject/function/, you can make a simple HTTP request to it.