Direct upload string to s3 from bootstrap modal not working - javascript

I observed a very strange behavior. If I set a button from web to upload string to S3, it works fine. But if I set a button from web to bring up a bootstrap modal, then from this modal I set a button to upload the string, it doesn't work.
Frontend is like below in both cases. The difference is whether clicking to run function 'saveToAWS' from web or from modal as 2-step-process, the latter returns xhr.status as 0.
function saveToAWS() {
var file = new File([jsonStr], "file.json", { type: "application/json" });
var xhr = new XMLHttpRequest();
var fn=file.name;
var ft = file.type;
xhr.open("GET", "/sign_s3_save?file-name=" + fn + "&file-type=" + ft);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
var response = JSON.parse(xhr.responseText);
console.log('signiture returned')
save_file(file, response.signed_request, response.url);
}
else {
alert("Could not get signed URL.");
}
}
};
xhr.send();
}
function save_file(file, signed_request, url) {
var xhr = new XMLHttpRequest();
xhr.open('PUT', signed_request);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log('200');
}
else {
alert('cannot upload file');
}
}
};
xhr.send(file);
}
Backend as Node.js, in order to get a signed URL:
app.get('/sign_s3_save', isLoggedIn, function (req, res) {
var fileName = req.query['file-name'];
var fileType = req.query['file-type'];
aws.config.update({ accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY });
var s3 = new aws.S3();
var ac = req.user._id;
var timenow = Date.now().toString();
var fileRename = ac + '/json/' + timenow + '.json';
var s3_params = {
Bucket: S3_BUCKET,
Key: fileRename,
Expires: 60,
ContentType: fileType,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3_params, function (err, data) {
if (err) {
console.log(err);
}
else {
var return_data = {
signed_request: data,
url: 'https://' + S3_BUCKET + '.s3.amazonaws.com/' + fileRename
};
res.write(JSON.stringify(return_data));
res.end();
}
});
});
Any suggestion, please?

Related

Can not send file from Controller Action to browser for download

I am sending a XMLHttpRequest to a MVC Controller and i am expecting to receive a file as a result.
When debugging with the browser i am getting a response that is ok , but i do not know why it is not as a file:
JS
window.submit=function () {
return new Promise((resolve, reject) => {
var form = document.getElementById("newTestForm");
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var method = form.getAttribute('method');
var action = form.getAttribute('action');
xhr.open(method, action);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response); //response looks ok...but no file starts downloading
}
else if (xhr.status != 200) {
reject("Failed to submit form with status" + xhr.status);
}
}
xhr.send(data);
});
}
Controller
[HttpPost]
[Route([Some Route])]
public async Task BenchAsync(object request)
{
try
{
string fileName = "results.txt";
object result = await service.RunAsync(request);
byte[] data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(result));
this.Response.ContentType = "application/octet-stream";
this.Response.ContentLength = data.Length;
using(MemoryStream stream=new MemoryStream(data))
{
await stream.CopyToAsync(this.Response.Body);
}
}
catch (Exception ex)
{
throw;
}
}
I have solved it thanks to this Post
It seems i had to transform the response into a BLOB , create a download link and point it towards this blob and the created link in order to download the file.
So the function looks like :
window.submit= function () {
return new Promise((resolve, reject) => {
var form = document.getElementById("newTestForm");
var data = new FormData(form);
var xhr = new XMLHttpRequest();
var method = form.getAttribute('method');
var action = form.getAttribute('action');
xhr.open(method, action);
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
var blob = new Blob([this.response], { type: 'image/pdf' });
let a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'mytext.txt';
a.click();
window.URL.revokeObjectURL(url);
}
else if (xhr.status != 200) {
reject("Failed to submit form with status" + xhr.status);
}
}
xhr.send(data);
});
}
P.S i do not know what the type of the blob is named for txt but it works as well , given the right extension.

How to set the argument "url" in xmlhttp.open() when I want to use Ajax to send/receive request with node.js

server.js can produce random number. So now I want to get a random number from the server and use xmlhttp to send a request. But the value of string is not changed when I load http://localhost:3000/index.html. What happen?
index.js is shown as follows:
$(document).ready(function() {
getRandomNum();
});
function getRandomNum() {
$(".button").each(function() {
var that = $(this);
that.click(function() {
var span = $("<span></span>").addClass("unread");
that.append(span);
span.text("...");
server(span);
});
});
}
function server(span) {
var string;
var xmlhttp = new XMLHttpRequest();
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
string = xmlhttp.responseText;
}
xmlhttp.open("GET","http://localhost:3000/", true);
xmlhttp.send();
span.text(string);
}
server.js is shown as follows:
var http = require('http');
var url = require('url');
var path = require('path');
var fs = require('fs');
var port = 3000;
http.createServer(function(req,res) {
var pathname = url.parse(req.url).pathname;
var mimeType = getMimeType(pathname);
if (!!mimeType) {
handlePage(req, res, pathname);
} else {
handleAjax(req, res);
}
}).listen(port, function(){
console.log('server listen on ', port);
});
function getMimeType(pathname) {
var validExtensions = {
".html" : "text/html",
".js": "application/javascript",
".css": "text/css",
".jpg": "image/jpeg",
".gif": "image/gif",
".png": "image/png"
};
var ext = path.extname(pathname);
var type = validExtensions[ext];
return type;
}
function handlePage(req, res, pathname) {
var filePath = __dirname + pathname;
var mimeType = getMimeType(pathname);
if (fs.existsSync(filePath)) {
fs.readFile(filePath, function(err, data){
if (err) {
res.writeHead(500);
res.end();
} else {
res.setHeader("Content-Length", data.length);
res.setHeader("Content-Type", mimeType);
res.statusCode = 200;
res.end(data);
}
});
} else {
res.writeHead(500);
res.end();
}
}
function handleAjax(req, res) {
var random_time = 1000 + getRandomNumber(2000);
var random_num = 1 + getRandomNumber(9);
setTimeout(function(){
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end("" + random_num);
}, random_time);
}
function getRandomNumber(limit) {
return Math.round(Math.random() * limit);
}
In your server(span) method, you initialize sending the request and immediately assigning the null string to the span by span.text(string) after this line xmlhttp.send();.
Once the response (random number) is received from the server, you are assigning the same to the variable string = xmlhttp.responseText; but not updating the same to the span.
Also, you haven't handled the response inside the onreadystatechange method.
I have modified your code below. I have created a test app and tested the same. Its working as you expected.
function server(span) {
var string;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange= function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
string = xmlhttp.responseText;
span.text(string);
}
};
xmlhttp.open("GET","http://localhost:3000/", true);
xmlhttp.send();
}

consuming API JSon calls through TVJS-tvOS

I am trying to play with tvOS, and I have small question regarding handling json call. I have to get some data through an API, let's say for sake of test that I am calling this link
http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%223015%22&format=json
I tried to use this function with some modification
function getDocument(url) {
var templateXHR = new XMLHttpRequest();
templateXHR.responseType = "json";
templateXHR.open("GET", url, true);
templateXHR.send();
return templateXHR;
}
but didn't work out. Any hints or help ?
If I need to use NodeJS, how can I do that ?
This is one that I got working. It's not ideal in many respects, but shows you something to get started with.
function jsonRequest(options) {
var url = options.url;
var method = options.method || 'GET';
var headers = options.headers || {} ;
var body = options.body || '';
var callback = options.callback || function(err, data) {
console.error("options.callback was missing for this request");
};
if (!url) {
throw 'loadURL requires a url argument';
}
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.onreadystatechange = function() {
try {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
callback(null, JSON.parse(xhr.responseText));
} else {
callback(new Error("Error [" + xhr.status + "] making http request: " + url));
}
}
} catch (err) {
console.error('Aborting request ' + url + '. Error: ' + err);
xhr.abort();
callback(new Error("Error making request to: " + url + " error: " + err));
}
};
xhr.open(method, url, true);
Object.keys(headers).forEach(function(key) {
xhr.setRequestHeader(key, headers[key]);
});
xhr.send();
return xhr;
}
And you can call it with the following example:
jsonRequest({
url: 'https://api.github.com/users/staxmanade/repos',
callback: function(err, data) {
console.log(JSON.stringify(data[0], null, ' '));
}
});
Hope this helps.
I tested this one out on the tvOS - works like a charm with jQuery's syntax (basic tests pass):
var $ = {};
$.ajax = function(options) {
var url = options.url;
var type = options.type || 'GET';
var headers = options.headers || {} ;
var body = options.data || null;
var timeout = options.timeout || null;
var success = options.success || function(err, data) {
console.log("options.success was missing for this request");
};
var contentType = options.contentType || 'application/json';
var error = options.error || function(err, data) {
console.log("options.error was missing for this request");
};
if (!url) {
throw 'loadURL requires a url argument';
}
var xhr = new XMLHttpRequest();
xhr.responseType = 'json';
xhr.timeout = timeout;
xhr.onreadystatechange = function() {
try {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (xhr.responseType === 'json') {
success(null, xhr.response);
} else {
success(null, JSON.parse(xhr.responseText));
}
} else {
success(new Error("Error [" + xhr.status + "] making http request: " + url));
}
}
} catch (err) {
console.error('Aborting request ' + url + '. Error: ' + err);
xhr.abort();
error(new Error("Error making request to: " + url + " error: " + err));
}
};
xhr.open(type, url, true);
xhr.setRequestHeader("Content-Type", contentType);
xhr.setRequestHeader("Accept", 'application/json, text/javascript, */*');
Object.keys(headers).forEach(function(key) {
xhr.setRequestHeader(key, headers[key]);
});
if(!body) {
xhr.send();
} else {
xhr.send(body);
}
return xhr;
}
Example queries working on Apple TV:
var testPut = function(){
$.ajax({
type: 'PUT',
url: url,
success: successFunc,
error: errFunc,
dataType: 'json',
contentType: 'application/json',
data: data2
});
}
var testGet = function(){
$.ajax({
dataType: 'json',
url: url,
success: successFunc,
error: errFunc,
timeout: 2000
});
}
var getLarge = function(){
$.ajax({
dataType: 'json',
url: url,
success: successFunc,
error: errFunc,
timeout: 2000
});
}
Did you call your function in the 'App.onLaunch'
App.onLaunch = function(options) {
var url = 'http://query.yahooapis.com/v1/public/yql?q=select%20item%20from%20weather.forecast%20where%20location%3D%223015%22&format=json';
var doc = getDocument(url);
console.log(doc);
}
Might be worth looking at https://mathiasbynens.be/notes/xhr-responsetype-json
I came across this question looking to accomplish the same thing, and was inspired by #JasonJerrett's answer, but found it a bit lacking because in my instance I am using an XML template built in Javascript like this:
// Index.xml.js
var Template = function() {
return `very long xml string`;
};
The issue is that you can't perform the XHR request inside the template itself, because the template string will be returned back before the XHR request actually completes (there's no way to return data from inside an asynchronous callback). My solution was to modify the resource loader and perform the XHR request there, prior to calling the template and passing the data into the template function:
ResourceLoader.prototype.loadResource = function(resource, dataEndpoint, callback) {
var self = this;
evaluateScripts([resource], function(success) {
if (success) {
// Here's the magic. Perform the API call and once it's complete,
// call template constructor and pass in API data
self.getJSON(dataEndpoint, function(data) {
var resource = Template.call(self, data);
callback.call(self, resource);
});
} else {
var title = "Failed to load resources",
description = `There was an error attempting to load the resource. \n\n Please try again later.`,
alert = createAlert(title, description);
Presenter.removeLoadingIndicator();
navigationDocument.presentModal(alert);
}
});
}
// From: https://mathiasbynens.be/notes/xhr-responsetype-json
ResourceLoader.prototype.getJSON = function(url, successHandler, errorHandler) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.onreadystatechange = function() {
var status;
var data;
if (xhr.readyState == 4) {
status = xhr.status;
if (status == 200) {
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
Then the template function needs to be modified to accept the incoming API data as a parameter:
// Index.xml.js
var Template = function(data) {
return 'really long xml string with injected ${data}';
};
You need to implement the onreadystatechange event on the XHR object to handle the response:
templateXHR.onreadystatechange = function() {
var status;
var data;
if (templateXHR.readyState == 4) { //request finished and response is ready
status = templateXHR.status;
if (status == 200) {
data = JSON.parse(templateXHR.responseText);
// pass the data to a handler
} else {
// handle the error
}
}
};
If you want to call the request on app launch, just add in application.js:
App.onLaunch = function(options) {
var javascriptFiles = [
`${options.BASEURL}js/resourceLoader.js`,
`${options.BASEURL}js/presenter.js`
];
evaluateScripts(javascriptFiles, function(success) {
if(success) {
resourceLoader = new ResourceLoader(options.BASEURL);
var index = resourceLoader.loadResource(`${options.BASEURL}templates/weatherTemplate.xml.js`, function(resource) {
var doc = Presenter.makeDocument(resource);
doc.addEventListener("select", Presenter.load.bind(Presenter));
doc.addEventListener('load', Presenter.request);
navigationDocument.pushDocument(doc);
});
} else {
var errorDoc = createAlert("Evaluate Scripts Error", "Error attempting to evaluate external JavaScript files.");
navigationDocument.presentModal(errorDoc);
}
});
}
In presenter.js add a method:
request: function() {
var xmlhttp = new XMLHttpRequest() , method = 'GET' , url = 'your Api url';
xmlhttp.open( method , url , true );
xmlhttp.onreadystatechange = function () {
var status;
var data;
if (xmlhttp.readyState == 4) {
status = xmlhttp.status;
if (status == 200) {
data = JSON.parse(xmlhttp.responseText);
console.log(data);
} else {
var errorDoc = createAlert("Evaluate Scripts Error", "Error attempting to evaluate external JavaScript files.");
navigationDocument.presentModal(errorDoc);
}
}
};
xmlhttp.send();
},

How to save binary data of zip file in Javascript?

I am getting below response from AJAX respose:
this is response of zip file.
please let me know how to save this filename.zip in Javascript. Inside the ZIP there is PDF file.
MY code is like this:
$.ajax({
url: baseURLDownload + "/service/report-builder/generateReportContentPDF",
beforeSend: function (xhr) {
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.responseType = 'arraybuffer'
},
type: "POST",
data: JSON.stringify(parameter),
contentType: "application/json",
success: function(result) {
console.log("ssss->"+result);
var base64String = utf8_to_b64(result);
//window.open("data:application/zip;base64,"+base64String); // It will download pdf in zip
var zip = new JSZip();
zip.add("PDFReport.pdf", result);
content = zip.generate();
location.href="data:application/zip;base64," + content;
$.mobile.loading('hide');
},
error: function(xhr){
console.log("Request Status: " + xhr.status + " Status Text: " + xhr.statusText + " " + xhr.responseText);
$.mobile.loading('hide');
showAlert("Error occured. Unable to download Report", "Message", "OK");
}
});
RESPOSE Console.log("ssss->"+result);
PK��Q��F���������������/crt_pdf_10204725.pdf��uX\M�8|p�����݃�;w�#p �ܝBp��݂�;|C�ھ�w������=O���]]�%�N�����#+�reup����������Y������̉�J����3)� O��C����F�M�P�&�����rA�#��7T.��z(%h��x�x0�0Z�-i��%q�e�M�����i�"�c��-/��j��齔/ļL瞄�0� �� >�o��[��6 멆�n��s�$�
�#>˘ '��wT�� ���3�36DK�+�̓�t6 ��r��sA:���x�<>n������'U��RLqA+���ݺ�BM��:4ĞP�}���:�}ߣP����?F)�9-�W0���2�{x��#2v8N.$V�>X=/�+�c}���ּ�\y���\*�J\��
���90�T�L� 3p���*Sfj(���PWWz��O�s�9]&����iO|�9�;�5��ʘdW�cl% �%;����u���%[�5������Q]$��[L>���yXg�9��2+&,iFs�Q�����u򪠵�.�E(�>W��+��M ؟E������i|���k�k�c蟴CcG�j��4s|x �F1�}��Y��,29�0M=-O����m\L��y��^On^���\���u��a���F9:zc�Sy�-�g��fu�n�C�T:{
��4&/
��LM9�98�
�&Pnc�!��m�r�~��)74�04��0�0������M�~"��.ikjG��M�-
Finally I got answer of my question:
https://github.com/eligrey/Blob.js/
https://github.com/eligrey/FileSaver.js/
Here is the code:
var xhr = new XMLHttpRequest();
xhr.open("POST", baseURLDownload + "/service/report/QCPReport", true);
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// alert("Failed to download:" + xhr.status + "---" + xhr.statusText);
var blob = new Blob([xhr.response], {type: "octet/stream"});
var fileName = "QCPReport.zip";
saveAs(blob, fileName);
}
}
xhr.responseType = "arraybuffer";
xhr.send(JSON.stringify(QCPParameter));
No dependancy.
Compatible with IE 10,11, Chrome, FF and Safari:
function str2bytes (str) {
var bytes = new Uint8Array(str.length);
for (var i=0; i<str.length; i++) {
bytes[i] = str.charCodeAt(i);
}
return bytes;
}
var xhr = new XMLHttpRequest();
xhr.open("POST", baseURLDownload + "/service/report/QCPReport", true);
xhr.setRequestHeader("Content-type","application/json");
xhr.setRequestHeader("Access-Control-Allow-Origin", "*");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
// alert("Failed to download:" + xhr.status + "---" + xhr.statusText);
var blob = new Blob([str2bytes(xhr.response)], {type: "application/zip"});
var fileName = "QCPReport.zip";
if (navigator.msSaveOrOpenBlob) {
navigator.msSaveOrOpenBlob(blob, filename);
} else {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display:none";
var url = window.URL.createObjectURL(blob);
a.href = url;
a.download = filename;
a.click();
window.URL.revokeObjectURL(url);
a.remove();
}
}
}
xhr.responseType = "arraybuffer";
xhr.send(JSON.stringify(QCPParameter));
Axios implementation:
const url = 'https://www.example.com/download-zip'
// Payload, eg list of docs to zip
const payload = { documents: ['id1', 'id2', 'id3'] }
// Axios options
const axiosOptions = {
responseType: 'arraybuffer',
headers: {
'Content-Type': 'application/json'
}
}
// Fetch data and save file
axios
.post(url, payload, axiosOptions)
.then((response) => {
const blob = new Blob([response.data], {
type: 'application/octet-stream'
})
const filename = 'download.zip'
saveAs(blob, filename)
})
.catch((e) => {
// Handle error
})
})
Note
saveAs is a function from file-saver package I've been using to handle saving the file.
For those of you using fetch, you can do this doing something like this.
fetch(url, config).
.then((response) => {
return response.arrayBuffer()
})
.then((data) => handleData(data))
In handleData, you will then instantiate the Blob object to handle the zip data.
Here is my Answer
you can avoid using blob and avoid using Filesaver.
This is how i wrote for one of my project using GET Method
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, true);
xmlHttp.setRequestHeader("Content-type","application/json");
xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "*");
xmlHttp.responseType= 'blob';
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
const downloadUrl = window.URL.createObjectURL(xmlHttp.response);
const link = document.createElement('a');
link.setAttribute('href', downloadUrl);
link.setAttribute('download', `filename.zip`);
link.style.display = 'none';
document.body.appendChild(link);
link.click();
window.URL.revokeObjectURL(link.href);
document.body.removeChild(link);
}
}
xmlHttp.responseType = "arraybuffer";
xmlHttp.send();

Filename not being used as AWS S3 name

I am using expressjs and trying to POST an image to AWS S3 that can be used throughout my app. I have been following this tutorial and while I am able to successfully upload an image, the filename that is being given is default_name every single time and I don't believe a file format is being attached to the string to give the file the proper image format. When I look at the s3upload.js script that is provided in the tutorial, I notice that default_name is ths standard name they provide for files, but I'm not sure why it is accepting my file without using its title.
events-create.ejs (Where I have the upload):
<!DOCTYPE HTML>
<html>
<head>
<% include ../partials/head %>
</head>
<body>
<% include ../partials/navigation %>
<div class="grid" id="create-event-container">
<div class="col-1-1">
<div id="create-event">
<h1><i>Create Event</i></h1>
<input type="file" id="files"/>
<p id="status">Please select a file</p>
<div id="preview"><img src="/images/event-placeholder.png"></div>
<form action="/admin/events/create" method="POST">
<input type="hidden" id="speaker-image" name="speakerImage" value="/images/event-placeholder.png" />
Name: <input type="text" name="name"><br>
Title: <input type="text" name="title"><br>
Company: <input type="text" name="company"><br>
Website: <input type="text" name="url"><br>
<input type="submit" value="Submit"><br>
</form>
</div>
</div>
</div>
<script type="text/javascript" src="/js/s3upload.js" async></script>
<script>
console.log("S3 Function Launched");
function s3_upload(){
var status_elem = document.getElementById("status");
var url_elem = document.getElementById("speaker-image");
var preview_elem = document.getElementById("preview");
var s3upload = new S3Upload({
file_dom_selector: 'files',
s3_sign_put_url: '/sign_s3',
onProgress: function(percent, message) {
status_elem.innerHTML = 'Upload progress: ' + percent + '% ' + message;
},
onFinishS3Put: function(public_url) {
status_elem.innerHTML = 'Upload completed. Uploaded to: '+ public_url;
url_elem.value = public_url;
console.log(public_url);
preview_elem.innerHTML = '<img src="'+public_url+'" style="width:300px;" />';
},
onError: function(status) {
status_elem.innerHTML = 'Upload error: ' + status;
console.log(status_elem.innerHTML);
}
});
}
/*
* Listen for file selection:
*/
(function() {
var input_element = document.getElementById("files");
input_element.onchange = s3_upload;
})();
</script>
</body>
</html>
routes.js:
var express = require('express');
var router = express.Router();
var Event = require('./models/eventsModel');
var http = require('http');
var path = require('path');
var aws = require('aws-sdk');
var AWS_ACCESS_KEY = process.env.AWS_ACCESS_KEY;
var AWS_SECRET_KEY = process.env.AWS_SECRET_KEY;
var S3_BUCKET = process.env.S3_BUCKET;
router.get('/sign_s3', function(req, res){
aws.config.update({accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY });
var s3 = new aws.S3();
var s3_params = {
Bucket: S3_BUCKET,
Key: req.query.s3_object_name,
Expires: 60,
ContentType: req.query.s3_object_type,
ACL: 'public-read'
};
s3.getSignedUrl('putObject', s3_params, function(err, data){
if(err){
console.log(err);
}
else{
var return_data = {
signed_request: data,
url: 'https://'+S3_BUCKET+'.s3.amazonaws.com/'+req.query.s3_object_name
};
res.write(JSON.stringify(return_data));
res.end();
}
});
});
router.route('/admin/events/create')
.post(function(req, res){
var events = new Event();
events.name = req.body.name;
events.title = req.body.title;
events.company = req.body.company;
events.url = req.body.url;
events.speakerImage = req.body.url;
events.save(function(err){
if (err)
res.send(err);
res.redirect(303, '/events');
});
})
.get(function(req, res){
Event.find(function(err, events){
if (err)
res.send(err);
res.render('pages/events-create.ejs');
});
});
s3upload.js:
(function() {
window.S3Upload = (function() {
S3Upload.prototype.s3_object_name = 'default_name';
S3Upload.prototype.s3_sign_put_url = '/signS3put';
S3Upload.prototype.file_dom_selector = 'file_upload';
S3Upload.prototype.onFinishS3Put = function(public_url) {
return console.log('base.onFinishS3Put()', public_url);
};
S3Upload.prototype.onProgress = function(percent, status) {
return console.log('base.onProgress()', percent, status);
};
S3Upload.prototype.onError = function(status) {
return console.log('base.onError()', status);
};
function S3Upload(options) {
if (options == null) options = {};
for (option in options) {
this[option] = options[option];
}
this.handleFileSelect(document.getElementById(this.file_dom_selector));
}
S3Upload.prototype.handleFileSelect = function(file_element) {
var f, files, output, _i, _len, _results;
this.onProgress(0, 'Upload started.');
files = file_element.files;
output = [];
_results = [];
for (_i = 0, _len = files.length; _i < _len; _i++) {
f = files[_i];
_results.push(this.uploadFile(f));
}
return _results;
};
S3Upload.prototype.createCORSRequest = function(method, url) {
var xhr;
xhr = new XMLHttpRequest();
if (xhr.withCredentials != null) {
xhr.open(method, url, true);
} else if (typeof XDomainRequest !== "undefined") {
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
xhr = null;
}
return xhr;
};
S3Upload.prototype.executeOnSignedUrl = function(file, callback) {
var this_s3upload, xhr;
this_s3upload = this;
xhr = new XMLHttpRequest();
xhr.open('GET', this.s3_sign_put_url + '?s3_object_type=' + file.type + '&s3_object_name=' + this.s3_object_name, true);
xhr.overrideMimeType('text/plain; charset=x-user-defined');
xhr.onreadystatechange = function(e) {
var result;
if (this.readyState === 4 && this.status === 200) {
try {
result = JSON.parse(this.responseText);
} catch (error) {
this_s3upload.onError('Signing server returned some ugly/empty JSON: "' + this.responseText + '"');
return false;
}
return callback(result.signed_request, result.url);
} else if (this.readyState === 4 && this.status !== 200) {
return this_s3upload.onError('Could not contact request signing server. Status = ' + this.status);
}
};
return xhr.send();
};
S3Upload.prototype.uploadToS3 = function(file, url, public_url) {
var this_s3upload, xhr;
this_s3upload = this;
xhr = this.createCORSRequest('PUT', url);
if (!xhr) {
this.onError('CORS not supported');
} else {
xhr.onload = function() {
if (xhr.status === 200) {
this_s3upload.onProgress(100, 'Upload completed.');
return this_s3upload.onFinishS3Put(public_url);
} else {
return this_s3upload.onError('Upload error: ' + xhr.status);
}
};
xhr.onerror = function() {
return this_s3upload.onError('XHR error.');
};
xhr.upload.onprogress = function(e) {
var percentLoaded;
if (e.lengthComputable) {
percentLoaded = Math.round((e.loaded / e.total) * 100);
return this_s3upload.onProgress(percentLoaded, percentLoaded === 100 ? 'Finalizing.' : 'Uploading.');
}
};
}
xhr.setRequestHeader('Content-Type', file.type);
xhr.setRequestHeader('x-amz-acl', 'public-read');
return xhr.send(file);
};
S3Upload.prototype.uploadFile = function(file) {
var this_s3upload;
this_s3upload = this;
return this.executeOnSignedUrl(file, function(signedURL, publicURL) {
return this_s3upload.uploadToS3(file, signedURL, publicURL);
});
};
return S3Upload;
})();
}).call(this);
You could either set the filename on the client side or the server side.
Client-side: In events-create.ejs, pass this parameter to S3Upload:
s3_object_name: $('input[type=file]').val().match(/[^\/\\]+$/)[0]
Server-side (Preferred method): In routes.js, replace all instances of req.query.s3_object_name with a unique filename. You can use req.query.s3_object_type to determine the extension you should put on the end of the filename. You want to use a unique filename here because everything is being stored in the same bucket and AWS automatically overwrites files with the same filename.
I came across the same issue, this is how i tackled it within my node controller:
aws.config.update({accessKeyId: AWS_ACCESS_KEY, secretAccessKey: AWS_SECRET_KEY});
var s3 = new aws.S3();
// Set Extension
switch(req.query.s3_object_type) {
case 'image/png':
var ext = '.png';
break;
case 'image/gif':
var ext = '.gif';
break;
case 'image/jpg':
case 'image/jpeg':
var ext = '.jpg';
break;
}
// Rename File
var name = Math.floor(new Date() / 1000);
// Set S3
var s3_params = {
Bucket: S3_BUCKET,
Key: 'blog/'+name+ext,
Expires: 60,
ContentType: req.query.s3_object_type,
ACL: 'public-read'
};
// Send S3
s3.getSignedUrl('putObject', s3_params, function(err, data){
if(err){
console.log(err);
}
else{
var return_data = {
signed_request: data,
url: 'https://'+S3_BUCKET+'.s3.amazonaws.com/'+name+ext
};
res.write(JSON.stringify(return_data));
res.end();
}
});
So as you can see a pretty simple solution to the problem, just check the extension and rename the file. Hope this helps.

Categories

Resources