here is my code
var storage = multer.diskStorage({
destination:function(req,file,cb){
cb(null,path.join(path.resolve('./'),"/images"))
},
filename:function(req,file,cb){
cb(null,file.fieldname+"-"+ Date.now())
}
});
in "/images",there are 2 files
they are same files
Related
I want the user to be able download images from the project /assets folder into an external publically accessible folder. This works fine on Android but in iOS everything saves under the app's unique ID directory so not sure if this possible. Essentially I want the user to save a photo from inside the app and then be able to open it easily from within their phone's default Photos app.
With the final photoPath var in the code below I can display the image in a <img tag using the DomSanitizer. Though still not sure how to make the file accessible on the user's system from outside the app.
this.http.get('/assets/img/' + item.img, { responseType: 'blob' })
.subscribe(res => {
const reader = new FileReader();
reader.onloadend = () => {
var base64data = reader.result;
await Filesystem.appendFile({
data: base64data.toString(),
path: item.file,
directory: FilesystemDirectory.Documents
})
const finalPhotoUri = await Filesystem.getUri({
directory: FilesystemDirectory.Documents,
path: item.file
});
let photoPath = Capacitor.convertFileSrc(finalPhotoUri.uri);
console.log("Photo Path: ", photoPath);
}
reader.readAsDataURL(res);
console.log(res);
});
I am using AWS S3 and Cloudfront to store images and render images on a webpage. I have managed to generate a signed URL using Cloudfront to render S3 Objects.
The problem is, I tried attaching that signed URL within an a tag for href='' tagger. I was hoping that, when users clicked on the link, it would direct them to the image through the web. Instead, the file is downloaded when a user clicks on the link.
How photo key is generated
var photoKey = $ctrl.clientDetail["_id"] + '/' + fileName;
I created a subdirectory for each user, and store the file in the respective subdirectory.
My Upload Function in AngularJS
s3.upload({
Key: photoKey,
Body: file,
ACL: 'public-read',
Metadata: {
'id': $ctrl.clientDetail["_id"],
'phone': $ctrl.phone
}
}, function(err, data){
if (err) {
$scope.uploadedFail = true;
console.log(err)
genericServices.setErrorInfo($scope.configErrorAddDocAlert, addDoc_reason);
}
else {
$scope.uploadedSuccess = true;
genericServices.setSuccessInfo($scope.configSuccessAddDocAlert, addDoc_success);
}
}
);
What I found interesting was that when I manually uploaded a file in a subdirectory in the AWS S3 console, the generated URL was able to serve the file through the web.
How do I make it, so that the Object within the bucket is not a downloadable file, but a link?
For those who faced the same problem, here is the solution.
When uploading, specify the content-type.
S3 Upload Process modified
s3.upload({
Key: photoKey,
Body: file,
ContentType: file.type,
Metadata: {
'id': $ctrl.clientDetail["_id"],
'phone': $ctrl.phone
}
}, function(err, data){
if (err) {
$scope.uploadedFail = true;
console.log(err)
genericServices.setErrorInfo($scope.configErrorAddDocAlert, addDoc_reason);
}
else {
$scope.uploadedSuccess = true;
genericServices.setSuccessInfo($scope.configSuccessAddDocAlert, addDoc_success);
}
}
);
Initially, the type was application/octet-stream, so it was only downloadable.
Thanks you #michael-sqlbot for the comment
I need to upload image from my ios application to server using node socket script.Below is my script that i have tried.I could not identify the issue.Please help me if any thing wrong or missing in script side or ios side.
socket.on('Upload_Image', function(data)
{
var multer = require('multer')
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'uploads/')
},
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
}
})
var upload = multer({ storage: storage }).single(data.file);
console.log(data.file);
app.post('/', function (req, res)
{
upload(req,res,function(req,res)
{
if(err)
{
console.log("error uploading file");
}
else
{
console.log("uploaded");
}
});
});
});
Above code - > data is the dictionary that i am passing from ios and data.file is the parameter name.
uploads -> is a folder where i need to upload image
==> ios code to call socket event
let msgDictionary = [
"file":UIImagePNGRepresentation(imageData)!];
APP_DELEGATE.socketIOHandler?.socket?.emit("Upload_Image",msgDictionary)
Alternate suggestions are also welcome.
I have a Meteor application deployed with nginx.
I try to upload images from the application to save the images on the server. When I'm in localhost, I save my images in the myapp/public/uploads folder. But, when I deploy, this folder become myapp/bundle/programs/web.browser/app/uploads. So, when I upload an image, it saved in a new folder in myapp/public/uploads. But so, I can't access to it. When I'm in localhost I access to my images like that : localhost:3000/uploads/myImage.png but when I do myAdress/uploads/myImage.png I access to the myapp/bundle/programs/web.browser/app/uploads folder and not the one where the images are saved (myapp/public/uploads).
This is my code to save images :
Meteor.startup(function () {
UploadServer.init({
tmpDir: process.env.PWD + '/app/uploads',
uploadDir: process.env.PWD + '/app/uploads',
checkCreateDirectories: true,
uploadUrl: '/upload',
// *** For renaming files on server
getFileName: function(file, formData) {
//CurrentUserId is a variable passed from publications.js
var name = file.name;
name = name.replace(/\s/g, '');
return currentTileId + "_" + name;
},
finished: function(fileInfo, formFields) {
var name = fileInfo.name;
name = name.replace(/\s/g, '');
insertionImages(name, currentTileId, docId);
},
});
});
So, do you know how can I do to save and access to my images when the application is deployed ? Maybe save the image in the myapp/bundle/programs/web.browser/app/uploads folder or access to the myapp/public/uploads folder with an url.
This is what we do.
Use an external dir for uploads, say, /var/uploads. Keeping the uploads in public folder makes the meteor app to reload in the dev environment, on any file upload.
Now, at local, use Meteor to serve these files at a certain url. In production, use nginx to serve the same at the same url.
For Development
1) Symlink your upload dir to a hidden folder in public.
eg:
ln -s /var/uploads /path/to/public/.#static
2) Serve the public hidden folder via Meteor by using:
The url /static will server the folder public/.#static by using the following code on the server. Ref: How to prevent Meteor from watching files?
var fs = require('fs'), mime = require('mime');
WebApp.rawConnectHandlers.use(function(req, res, next) {
var data, filePath, re, type;
re = /^\/static\/(.*)$/.exec(req.url);
if (re !== null) {
filePath = process.env.PWD + '/public/.#static/' + re[1];
try {
stats = fs.lstatSync(filePath);
if (stats.isFile()) {
type = mime.lookup(filePath);
data = fs.readFileSync(filePath, data);
res.writeHead(200, {
'Content-Type': type
});
res.write(data);
res.end();
}
}
catch (e) {
// console.error(filePath, "not found", e); // eslint-disable-line no-console
next();
}
}
else {
next();
}
});
For production
1) Use nginx for serving the upload dir
server {
...
location /static/ {
root /var/uploads;
}
...
}
That's it. /static will server the content of your uploads dir i.e. /var/uploads
I've a problem with moving a camera photo to the persistent storage under iOS 7 (Cordova 3.4.0-0.1.3 - File API 1.0.1).
I can capture the photo and when I move the file to the persistent storage it seems that there is no error, I also receive a file path with new_entry.fullPath like /my_folder/12345678.jpg.
But when I append the new image to the body with that url it seems that there is no image (blank image will be added). I've tried it also with "file://" in the url, but this makes no difference.
I'm also a little bit confused, because the new_entry.toURL() method returned an url containing a folder named "temporary" (e.g. cdvfile://localhost/temporary/my_folder/12345678.jpg), but I use the persistent storage. Is that correct under iOS?
This is my relevant code for that function:
var app = {
capturePhoto: function () {
if (!navigator.camera) {
alert('Camera API not supported');
}
navigator.camera.getPicture( app.cameraSuccess, app.cameraError, {
quality: 50,
destinationType: Camera.DestinationType.FILE_URI
});
},
cameraSuccess: function (imageData) {
console.log('cameraSuccess: '+imageData);
app.movePhoto( imageData );
},
movePhoto: function (file){
alert(file);
window.resolveLocalFileSystemURI( file , app.resolveOnSuccess, app.resOnError);
},
resolveOnSuccess: function (entry){
var d = new Date();
var n = d.getTime();
//new file name
var newFileName = n + ".jpg";
var myFolderApp = "my_folder";
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, function(fileSys) {
fileSys.root.getDirectory( myFolderApp,
{create:true},
function(directory) {
entry.moveTo(directory, newFileName, function(new_entry){
path = new_entry.fullPath;
url = new_entry.toURL();
console.log(path+"\n"+url);
alert( path+"\n"+url );
jQuery('body').append('<img src="'+path+'" />');
}, app.resOnError);
},
app.resOnError);
},
app.resOnError);
},
resOnError: function(error) {
alert('Error '+error.code+': '+error.message);
},
}
27/5/2014 UPDATE: Version 1.1.0 was released since than, therefore no need to use dev branch anymore.
It's a bug in cordova: https://issues.apache.org/jira/browse/CB-6148
It's already fixed in dev branch. You can update to dev branch with those steps:
remove the plugin:
cordova plugin rm org.apache.cordova.file
install the plugin (we have to use the git syntax in this case):
cordova plugin add https://github.com/apache/cordova-plugin-file.git#dev
check the iOS build > Targets > Your app target > Build phases > Compile Sources
add (if not added)
CDVFile.m
CDVLocalFilesystem.m
CDVAssetLibraryFilesystem.m