How to get uploaded image url in sails js - sails.js

I am successfully able to upload files. But i need to get the url.
For eg: localhost:1337/images/image.jpg
I have tried to do this but not successful yet
Sails version i am using is 1.2.3
Here is my code for upload
try{
var uploadFile = req.file('images');
uploadFile.upload({ dirname: '../../assets/images' }, function onUploadComplete(err, files) {
if (err)
return res.serverError(err);
return res.json({ status: 200, file: files });
});
}catch(err){
return res.serverError(err);
}
localhost:1337/images/image.jpg
This says Not Found

You may want to use sails-hook-uploads and check out https://github.com/mikermcneil/ration
Check this file too
https://github.com/mikermcneil/ration/blob/master/api/controllers/things/upload-thing.js

Related

Why is my Upload-File POST not working using NEST.JS and Multer?

I try to make a simple file upload REST interface using NEST.JS and MULTER -- but its not working. I am able to POST a binary file debug.log to the URL, and I see the "Hello undefined" message, but the uploaded file neither is created at the given folder uploads nor it is rejected because the extension is not correct - according to the file filter.
However, no exception or error is shown.
Why is multer not working?
Why is the #Uploadedfile() file shown as undefined?
Thanks
import { Controller, Post, Request, UseInterceptors, FileInterceptor, UploadedFile, HttpCode, HttpException, HttpStatus } from '#nestjs/common';
import { diskStorage, File } from 'multer';
const path = require('path');
const myStorage = diskStorage({
destination: function (req, file, callback) {
callback(null, './uploads/');
},
limits: { fileSize: 1000000 },
fileFilter: function (req, file, cb) {
const extension = path.extname(file.originalname).toLowerCase()
const mimetyp = file.mimetype
if (extension !== '.jpg' || mimetyp !== 'image/jpg') {
cb(new HttpException('Only images are allowed', HttpStatus.NOT_ACCEPTABLE));
}
cb(null, true);
},
filename: function (req, file, callback) {
callback(null, file.fieldname + '_' + Date.now() + '.jpg');
}
});
#Controller('documents')
export class DocumentsController {
#Post()
#HttpCode(HttpStatus.OK)
#UseInterceptors(FileInterceptor('file', { storage: myStorage }))
public async addDocument(#UploadedFile() file): Promise<any> {
console.log("Hello " + file);
}
}
I know it's a late reply for the person who asked this question, but the answer is for the people who will face it in the future.
First, check the nestjs documentation
If MulterModule registered in the *.module.ts file it creates the upload directory outside of the src folder. which is a good practice.
MulterModule.register({
dest: './upload',
});
If there is a need to change the destination directory use destination: String|callback from DiskStorageOptions or dest:string from FileInterceptor. For upload path use like src/../upload to keep the folder outside the src directory.
Other problems from the above code mentioned in the question:
I see the "Hello undefined" message
reason console.log("Hello " + file); here file is Object and trying concatenate with String.
change it to console.log("Hello ", file);
the extension is not correct, no exception or error is shown
fileFilter: function (req, file, cb) {
const extension = path.extname(file.originalname).toLowerCase()
const mimetyp = file.mimetype
if (extension !== '.jpg' || mimetyp !== 'image/jpg') {
cb(new HttpException('Only images are allowed', HttpStatus.NOT_ACCEPTABLE));
}
cb(null, true);
}
Here need to add a return.

Uploading large files (200+ mbs) from by ajax to sharepoint 2013 on premise

I'm trying to upload files to a library on sharepoin 2013 on premise by Ajax. I'm using the following code:
function uploadFileee(file) {
// var file = element.files[0];
console.log(file);
var reader = new FileReader();
reader.onload = function (e) {
enviar(e.target.result, file.name);
}
reader.onerror = function (e) {
alert(e.target.error);
}
//reader.readAsArrayBuffer(file);
reader.readAsArrayBuffer(file);
function enviar(file, name) {
var url = String.format(
"{0}/_api/Web/Lists/getByTitle('{1}')/RootFolder/Files/Add(url='{2}', overwrite={3})",
_spPageContextInfo.webAbsoluteUrl, "TreinamentoLib", name, "true");
console.log(url);
jQuery.ajax({
url: url,
type: "POST",
data: file,
processData: false,
headers: {
Accept: "application/json;odata=verbose",
"X-RequestDigest": jQuery("#__REQUESTDIGEST").val()
},
success: function (data) {
console.log("sucesso");
},
error : function(err)
{
console.log("erro");
}
})
}
}
As long the file is below 200mb's, it works just fine, but bigger than that, the browser crashes.
Chunks just work on the online version of sharepoint.. cound't make it work on On Premise.
Already though on creating an webApi in C# to receive the chunks and group it together and upload it to the library..
Anyone have ever done something like it? does anyone have any sugestion?
In SharePoint On Premise, you can try to increase the maxRequestLength="51200" executionTimeout="999999" in the web.config file at "C:\Inetpub\wwwroot\wss\VirtualDirectories\< Virtual Directory >" folder.
Or check maximum upload size for the web application : Central Admin> Application Management> Manage Web Applications> Select the desired web app and click General Settings on the ribbon.

How upload and save image using Sails and MongoDB

I'm working on a project and I'm using a backend sails js, a MongoDB as database and front-end React js.
I have a problem on the upload image.
Here is the code Sails backend and when I test it in PostMan, I got this result (result test PostMan), and the image is not stored in the specified folder but a value containing id and name of file is inserted in MongoDB,
uploadFile: function (req, res) {
var image= req.file('avatar');
image.upload({
adapter: require('skipper-gridfs'),
uri: 'mongodb://localhost:27017/name_db.name_collection',
dirname: '../../assets/images/'
}, function (err, filesUploaded) {
if (err){
return res.header("Access-Control-Allow-Origin", "*");
/*res.negotiate(err);*/res.json(err);
}
else{
return
res.header("Access-Control-Allow-Origin", "*"); res.ok({
files: filesUploaded,
textParams: req.params.all()
});
}
});
},
result test postMan
And here is the Reactjs front-end code
_handleSubmit(e) {
e.preventDefault();
// TODO: do something with -> this.state.file
fetch('http://localhost:1337/uploadPhoto/logos', {
method: 'POST',
body: JSON.stringify({avatar:this.state.file})
})
.then((response) => response.json())
.catch((err) => { console.log(err); });
}
Sails version 0.12,
React version 15.5,
and MongoDB version 3.4.9.
Thanks for your help
There is no dirname parameter for skipper-gridfs adapter because the file won't be stored onto the local file system.
Skipper will store the file into the MongoDB database.
U need to send it as form Data
let formData = new FormData()
console.log(values);
await formData.append('profile_picture',values.profile_picture.rawFile,values.profile_picture)
await fetch('http://localhost:1337/api/moderators',{
body:formData,
method:'POST',
credentials:'include' //If Using Session for react-app instead of JWT token
})

How send string/image base64 to Sailsjs - Skipper with ajax

Currently I am capturing the image of the camera, this Base64 format,and I'm sending through ajax.
xhr({
uri: 'http://localhost:1337/file/upload',
method: 'post',
body:'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAA...'
}
0 file(s) uploaded successfully!
Here is a nice link that will guide you to do send an image from an Ajax Client to an ajax server.
http://www.nickdesteffen.com/blog/file-uploading-over-ajax-using-html5
You can read this sails documentation to receive files on a sails server :
http://sailsjs.org/documentation/reference/request-req/req-file
You can do as the following example :
Client side ( ajax ):
var files = [];
$("input[type=file]").change(function(event) {
$.each(event.target.files, function(index, file) {
var reader = new FileReader();
reader.onload = function(event) {
object = {};
object.filename = file.name;
object.data = event.target.result;
files.push(object);
};
reader.readAsDataURL(file);
});
});
$("form").submit(function(form) {
$.each(files, function(index, file) {
$.ajax({url: "/ajax-upload",
type: 'POST',
data: {filename: file.filename, data: file.data}, // file.data is your base 64
success: function(data, status, xhr) {}
});
});
files = [];
form.preventDefault();
});
Server side ( sails ) :
[let's say you have a model Picture that take an ID and a URL]
[here is a sample of Picture controller, just to give you an idea]
module.exports = {
uploadPicture: function(req, res) {
req.file('picture').upload({
// don't allow the total upload size to exceed ~10MB
maxBytes: 10000000
},
function onDone(err, uploadedFiles) {
if (err) {
return res.negotiate(err);
}
// If no files were uploaded, respond with an error.
if (uploadedFiles.length === 0){
return res.badRequest('No file was uploaded');
}
// Save the "fd" and the url where the avatar for a user can be accessed
Picture
.update(777, { // give real ID
// Generate a unique URL where the avatar can be downloaded.
pictureURL: require('util').format('%s/user/pictures/%s', sails.getBaseUrl(), 777), // GIVE REAL ID
// Grab the first file and use it's `fd` (file descriptor)
pictureFD: uploadedFiles[0].fd
})
.exec(function (err){
if (err) return res.negotiate(err);
return res.ok();
});
});
}
};
Hope this will help in your research.
I also recommand you to use Postman to test your API first, then code your client.

Getting Time-Out Error While Posting Data

js.I am trying to create a file upload using node.js and mongodb.I am getting timeout error in posting data.The code that i use is:
app.post('/photos/new', function(req, res) {
var photo = new Photo();
req.form.complete(function(err, fields, files) {
if(err) {
next(err);
} else {
ins = fs.createReadStream(files.file.path);
ous = fs.createWriteStream(__dirname + '/static/uploads/photos/' + files.file.filename);
util.pump(ins, ous, function(err) {
if(err) {
next(err);
} else { photos.save({
filename: files.file.filename,
file: files.file.path
}, function(error, docs) {
res.redirect('/photos');
});
}
});
//console.log('\nUploaded %s to %s', files.photo.filename, files.photo.path);
//res.send('Uploaded ' + files.photo.filename + ' to ' + files.photo.path);
}
});
});
I get the following error when i click on the submit button.
Error: Timeout POST /photos/new
at Object._onTimeout (/home/nodeexmple/node_modules/connect-timeout/index.js:12:22)
at Timer.ontimeout (timers_uv.js:84:39)
Please help.
see this answer...
Error: parser error, 0 of 4344 bytes parsed (Node.js)
Also u can use req.clearTimeout() as suggested above by alessioalex.
I belive this part of your code is creating problems that u should avoid.
photos.save({
filename: files.file.filename,
file: files.file.path
}, function(error, docs) {
res.redirect('/photos');
});
Instead use like this:
var post = new Post();
post.filename=files.file.filename;
post.file=files.file.path;
And then something like this:
post.save(function(err) {
if (err)
return postCreationFailed();
req.flash('info', 'photos Succesfully Uploaded');
res.redirect('were u want to redirect');
});
Hope this solves your issue.
You are using the connect-timeout module so that is shows a message to your users in case the page takes more than X seconds to load (server-side).
It's obvious that the upload page might be taking more than that, so what you should do in your upload route is to clear the timeout like this:
app.post('/photos/new', function(req, res) {
req.clearTimeout();
...
Read more about connect-timeout on its github page.