I am working on a file uploader for my app and I settled on Filepicker.io. Everything is working fine except for one thing..When I upload an image to S3 I can only upload the URL that Filepicker returns (not the image itself).
The below is successful, but
Template.new_aphorism.events({
'change #attachment': function(event){
var savedFile = JSON.stringify(event.fpfile);
var parsedJSON = eval('('+savedFile+')');
var url=parsedJSON.url;
$('input[name=new_aphorism_image]').val(url);
console.log("saved file is:" + savedFile);
console.log(url);
filepicker.store(url, {location: 'S3'}, function(fpfile){
output.html('Uploaded: '+fpfile.filename+'');
}, function(fperror){
output.text(fperror.toString());
}, function(progress){
output.text("Uploading... ("+progress+"%)");
});
}
});
I get back as my message:
File stored in S3 at VnAa2YsOS6wOECNMWpwn_temp.txt and available at https://www.filepicker.io/api/file/vVtWTOl7QqOJ7gPmXkHQ
I have tried passing this and event.fpfile into my filepicker.store function but it just doesn't work.
Solved.
In the same function:
var file = event.fpfile;
filepicker.store(file, {location: 'S3'}, function(fpfile){
Related
I am trying to upload image to an Etsy listing via their API v2. Their documentation have code example of image upload in PHP, in which the POST request body parameter is given like this
$params = array('#image' => '#'.$source_file.';type='.$mimetype);
How would I go about replicating this in JavaScript? I have tried sending the image blob as the image parameter but it does not seem to be working.
Edit: I am using npm oauth package. Here is my complete code that I am using to call the API.
var oauth1 = new OAuth1.OAuth(
'https://openapi.etsy.com/v2/oauth/request_token?scope=email_r%20listings_r%20listings_w%20listings_d',
'https://openapi.etsy.com/v2/oauth/access_token',
'api_key',
'api_secret',
'1.0A',
null,
'HMAC-SHA1'
);
oauth1.post(
'https://openapi.etsy.com/v2/listings/915677000/images',
req.user.etsy.oauth_token,
req.user.etsy.oauth_token_secret,
{
'listing_id': 915677000,
'image': <image has to go here>
},
'multipart/form-data',
function (e, data, response){
if (e) console.error(e);
// let body = JSON.parse(data);
console.log(data);
res.redirect('/create-listings')
});
I'm using this module to upload images via socket.io.
Here's the client side code:
<img src="/img/avatar-2-128.png" alt="" id="signinbox_photo"> //avatar-2-128.png is an avatar that will be replaced
<input type="file" id="siofu_input" />
//upload the image to the server
var uploader = new SocketIOFileUpload(socket);
uploader.listenOnInput(document.getElementById("siofu_input"));
socket.on('update photo', function(data){ //update the src attr of the img tag
var signinbox_photo = $('#signinbox_photo');
signinbox_photo.attr("src",`/img/user_images/${data.id}.jpg`);
});
Server side:
var fs = require('fs');
var siofu = require("socketio-file-upload");
io.sockets.on('connection', function(socket) {
var uploader = new siofu();
var dir = "./public/img/user_images/"
uploader.dir = dir;
uploader.listen(socket); //save the file
uploader.on("saved", function(event){
fs.rename(dir + event.file.name, dir + socket.id + ".jpg", function(err) { //replace the file name to socket id
if ( err ) console.log('ERROR: ' + err);
});
io.sockets.emit('update photo', {id: socket.id}) //emit to client so it updates the src of the image
});
});
When the user uploads a picture, it works and everything is as expected, but when the user uploads again, it replaces the file in the server but doesn't update the src of the image in the client. Any suggestion would be appreciated. Thank you.
This is because everytime you upload image, the image name is same and there is no way for browser to not know that you have uploaded different image with same name. There is workaround though. You can add random number as query parameter while assigning the src in client side like this :
//upload the image to the server
var uploader = new SocketIOFileUpload(socket);
uploader.listenOnInput(document.getElementById("siofu_input"));
socket.on('update photo', function(data){ //update the src attr of the img tag
var signinbox_photo = $('#signinbox_photo');
signinbox_photo.attr("src",`/img/user_images/${data.id}.jpg?r=${Math.random()}`);
});
Currently I am using the following approach where it is giving details of file but not the actual object it seems like one we get from in javascript/jQuery. Does any one having the clue how to get the file object from File URI /native URI from mobile ios/android filesystem using cordova and javascript?
Below is the snippet I am using currently..
window.resolveLocalFileSystemURL(
filepath,
function(fileEntry) {
fileEntry.file(
function(file) {
var reader = new FileReader();
reader.onloadend = function() {
var imgBlob = new Blob([this.result], {type: "image/jpeg"});
var uploadedFile = imgBlob;
uploadedFile.name = file.name;
alert("Importing Asset from Camera.. " + uploadedFile.name);
alert(uploadedFile.type);
alert(uploadedFile.size);
importAsset(uploadedFile);
};
reader.readAsArrayBuffer(file);
},
function(error) { alert("Error in fileEntry.file():" + error) })
},
function(error) { alert("Error in window.resolveLocalFileSystemURL():" + error) }
);
Note: FileTransfer.upload() will not work in my case.
Above snippet I am using after taking from Append image file to form data - Cordova/Angular after going through the existing Q&A from #SO
Base64 Image Upload will work both in iOS/Android as I have tried:
As for iOS There is only one way to show image is using base64 format.You can use cordova-camera-plugin to to generate base64 image and put on img tag of HTML.I have set the flag to get data in jpeg,base64 in camera plugin.
<img id="cardImg">
Store the base64 image in javascript variable as:
var imgdata=data:image/jpeg;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==
Then Simply pass data to img tag of HTML as:
cardImg.src=imgdata;
Done!
I uploaded a pdf file to parse and it is visible in the data browser, but when I try to view it it says failed to load. I believe that my upload code is correct because it works for .docx files but not .pdf. Any ideas? Here is my code
function uploadFile (uploadId,fileName){
var fileUploadControl = $("#fileUpload")[0];
if(fileUploadControl.files.length>0){
var file = fileUploadControl.files[0];
var parseFile = new Parse.File(fileName,file);
parseFile.save().then(function(){
console.log("nsucciess");
//file has been saved to parse
},function(error){
//file could not be read or saved
console.log("error");
});
//var currentUser = Parse.User.current();
//currentUser.set(fileName,parseFile);
var ProjectFile = Parse.Object.extend("ProjectFile");
var projectFile = new ProjectFile();
projectFile.set("file",parseFile);
projectFile.save(null,{
success:function(projectFile){
console.log("success");
}
});
alert("everything works");
}
else{
alert("oh no");
}
}
Just solved: you have to add https://docs.google.com/viewer?url= before the link provided by Parse.com. For example: var yourUploadedPdfLink = "http://files.parsetfss.com/56accfec-1956-xxxxxx-abe8-xxxxxx/tfss-a7076e9c-xxxx-45fe-a8e8-xxxxxxx-MYDOCUMENT.pdf" To read it: "https://docs.google.com/viewer?url=" + yourUploadedPdfLink
And it'll works. So, you can't read pdf files clicking on them from Parse.com dashboard (at the moment).
i am capturing image with cordova using reference:
http://docs.phonegap.com/en/2.7.0/cordova_camera_camera.md.html
It's working fine. But when i click on save, the image is not saved/ stored in my phone.
Is there any extra js required apart from the code?
Or please tell me if there is any method to store image in a particular folder.
Thanks in advance.
Try like the following. It will save the image in the sample folder and also randomfilename should be you file name of taken image(generate new name every time using randomNumber generation or use the default camera returned file name).
navigator.camera.getPicture(function(imageData) {
var directory = "sampleApp/";
var randomFileName = "sampleimg.png"; // this should be the filename
saveImage(imageData,randomFileName,directory);
}, onFail, {
quality : 50,
destinationType : Camera.DestinationType.FILE_URI
});
function saveImage(imageData,fileName,directory){
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function gotFile(fileSystem) {
fileSystem.root.getDirectory(directory, {create: true}, function fileSystemSuccess(fileSystem){
fileSystem.getFile("dummy.txt",{create: true,exclusive:false},function gotFileEntry(fileEntry){
var path = fileEntry.fullPath.replace("dummy.txt","");
fileEntry.remove();
var fileTransfer = new FileTransfer();
fileTransfer.download(imageData, path+""+fileName,function(theFile){
alert("File Downloaded Successfully");
},function(error){
alert("File Download Failed"+ error.code);
});
},fail);
});
}, fail);
}
function fail(e){
alert("Error Occured"+ e.code);
}