upload a file using angular, express and mongodb's gridfs - mongodb

I am new to these technologies and hence have limited knowledge on how to upload a file. During my research, I have seen ngUpload and other javascript/directive based solutions. However, I am trying the following and not sure what else I am missing to complete it.
I am trying to upload file after creating a blog using angular-express-blog application. I have the following code
In view.jade
fieldset
h5 Add Media
form(name='theForm', enctype="multipart/form-data")
.clearfix
label Document Name
.input: input(ng-model='form.docName', name='docName', type='text')
.clearfix
label File
.input: input(ng-model='form.file', type="file", name="file")
.actions
button(ng-click="uploadFiles('/page3files')") Upload Files
the controller, I do need to return to the uploadfile page hence, I am passing in /page3files.
$scope.uploadFiles = function( path ) {
//alert("upload files clikced");
$http.post('/api/uploadFile', $scope.form).
success(function(data) {
$scope.form.docName='';
$scope.form.file='';
$location.path(path);
});
};
In the express routes file
exports.uploadFile = function (req, res) {
console.log("doc name: " + req.body.docName);
console.log("file name: " + req.body.file.name);
console.log("file path: " + req.body.file.path);
res.json(true);
};
Unfortunately, I am getting an exception at req.body.file.name saying cannot read property 'name' of undefined.
Any assistance is much appreciated.
Thanks,
Melroy

for the $http.post() to be able to upload files you need to set some configurations.
headers : {'Content-Type': undefined},
transformRequest: angular.identity
You can use the simple/lightweight angular-file-upload directive that takes care of that for you.
It supports drag&drop, file progress and file upload for non-HTML5 browsers with FileAPI flash shim.
<div ng-controller="MyCtrl">
<input type="file" ng-file-select="onFileSelect($files)" multiple>
</div>
JS:
//inject angular file upload directive.
angular.module('myApp', ['angularFileUpload']);
var MyCtrl = [ '$scope', '$upload', function($scope, $upload) {
$scope.onFileSelect = function($files) {
//$files: an array of files selected, each file has name, size, and type.
for (var i = 0; i < $files.length; i++) {
var $file = $files[i];
$upload.upload({
url: 'my/upload/url',
file: $file,
progress: function(e){}
}).then(function(data, status, headers, config) {
// file is uploaded successfully
console.log(data);
});
}
}
}];
There are more info on the README page and there is a Demo page

You can send file data with FormData object. For Example:
HTML:
<fieldset>
<legend>Upload Video</legend>
<input type="file" name="photo" id="photo">
<input type="button" ng-click="uploadVideo()" value="Upload">
</fieldset>
JS:
$scope.uploadVideo = function () {
var photo = document.getElementById("photo");
var file = photo.files[0];
var fd = new FormData(); //Create FormData object
fd.append('file', file);
$http.post('/uploadVideo', fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
}).success(function (data) {
// Do your work
});
};

Related

Upload files to SharePoint Online using SPHttpClient in an spfx webpart

I'm trying to upload a file using SPHttpClient in a spfx webpart.
The code I'm trying is
const spOpts:ISPHttpClientOptions={body: { my: "bodyJson" } };
contextDetails.spHttpClient.post(url,SPHttpClient.configurations.v1, spOpts)
.then(response => {
return response;
})
.then(json => {
return json;
}) as Promise<any>
But I'm not sure how to add content of the file to this httpClient API.
I guess we have to add content of file to spOpts in body parameter. I'm not sure though.
Any help is appreciated.
Thanks.
Assuming that you are using and input file tag as below:
<input type="file" id="uploadFile" value="Upload File" />
<input type="button" class="uploadButton" value="Upload" />
You can then register the handler of the uploadButton as below:
private setButtonsEventHandlers(): void {
this.domElement.getElementsByClassName('uploadButton')[0].
addEventListener('click', () => { this.UploadFiles(); });
}
Now, in the UploadFiles method, you can add the file's content and other necessary headers. Also, assuming that you are uploading the file to a document library, you can use the below snippet to upload a file to it. Modify it as per your site url and doc lib name:
var files = (<HTMLInputElement>document.getElementById('uploadFile')).files;
//in case of multiple files,iterate or else upload the first file.
var file = files[0];
if (file != undefined || file != null) {
let spOpts : ISPHttpClientOptions = {
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
},
body: file
};
var url = `https://<your-site-url>/_api/Web/Lists/getByTitle('Documents')/RootFolder/Files/Add(url='${file.name}', overwrite=true)`
this.context.spHttpClient.post(url, SPHttpClient.configurations.v1, spOpts).then((response: SPHttpClientResponse) => {
console.log(`Status code: ${response.status}`);
console.log(`Status text: ${response.statusText}`);
response.json().then((responseJSON: JSON) => {
console.log(responseJSON);
});
});
}

How to replace Angular2 Http to upload files?

The following code attempts to send a file from an Angular2 app. It always end-up in the REST API not being able to recognize the file in the request it is receiving. (Even if the content seams to be there !)
After spending hours searching StackOverflow and countless other online sources, i came to the conclusion that the most recent version of Angular2 Http module/service should now be capable of handling file uploads. (The fact that it wasn't able to do so in the past is just amazing !)
See this article or even this git sample.
If i am to use an external lib like ng2-file-upload, it needs to be able to replace Angular2::Http with as little modification as possible to the following code. (i.e. I cannot change the HTML form.)
Component.html
<form [formGroup]="profileForm" (ngSubmit)="onSubmit()" novalidate>
<label>Votre avatar !</label>
<input class="form-control" type="file" name="avatar" (change)="imageUpload($event)" >
Component.ts
imageUpload(e) {
let reader = new FileReader();
//get the selected file from event
let file = e.target.files[0];
reader.onloadend = () => {
this.image = reader.result;
}
reader.readAsDataURL(file);
}
onSubmit() {
if (this.image){
this.authService.setAvatar(this.image).subscribe(
d => {
//Do Nothing... Will navigate to this.router.url anyway so...
},
err =>{
this.errorMessage = err;
console.log(err);
}
);
}
}
authService.ts
setAvatar(image:any){
let form: FormData = new FormData();
form.append('avatar', image);
return this.http.post (Config.REST_URL + 'user/setAvatar?token=' +localStorage.getItem('token'), form,
{headers: new Headers({'X-Requested-With': 'XMLHttpRequest' })}
).catch(this.handleError);
}
REST_API Php (LARAVEL)
public function setAvatar(Request $request){
if($request->hasFile("avatar")) { // ALWAYS FALSE !!!!
$avatar = $request->file("avatar");
$filename = time() . "." . $avatar->getClientOriginalExtension();
Image::make($avatar)->fit(300)->save(public_path("/uploads/avatars/" . $filename));
return response()->json(['message' => "Avatar added !"], 200);
}
return response()->json(['message' => "Error_setAvatar: No file provided !"], 200);
}
Content of the Request Payload (As seen from Chrome Inspect/Network)
------WebKitFormBoundary8BxyBbDYFTYpOyDP
Content-Disposition: form-data; name="avatar"
Should be more like...:
Content-Disposition: form-data; name="avatar"; filename="vlc926.png"
Content-Type: image/png
Turns out Angular2's Http can now send files... And it's super easy !.... I just can't believe there are just no documentation out there showing this !
Except this one. (Credits to MICHAƁ DYMEL)
The HTML
<input #fileInput type="file"/>
<button (click)="addFile()">Add</button>
Component.ts
#ViewChild("fileInput") fileInput;
addFile(): void {
let fi = this.fileInput.nativeElement;
if (fi.files && fi.files[0]) {
let fileToUpload = fi.files[0];
this.uploadService
.upload(fileToUpload)
.subscribe(res => {
console.log(res);
});
}
}
The service.ts
upload(fileToUpload: any) {
let input = new FormData();
input.append("file", fileToUpload);
return this.http.post("/api/uploadFile", input);
}

Sending images with AngularJS and NodeJS

Hi I am making a service to send images with users' information. For example, name, phone number, and their images to upload.
I am planning to use ng-file-upload, one of AngularJS custom dependency. And then, I am going to use Nodemailer to send all the information and images to somewhere else.
But my question is can I send other text data along with ng-file-upload? And second is can I send images with other text data through nodemailer?
Although OP has found a solution in the end, since I had the same problem I figured I'd post the whole code here for others who might struggle with that.
So here is how I combined ng-file-upload and nodemailer to upload and send attachments by e-mail using Gmail:
HTML form:
<form name="postForm" ng-submit="postArt()">
...
<input type="file" ngf-select ng-model="picFile" name="file" ngf-max-size="20MB">
...
</form>
Controller:
app.controller('ArtCtrl', ['$scope', 'Upload', function ($scope, Upload) {
$scope.postArt = function() {
var file = $scope.picFile;
console.log(file);
file.upload = Upload.upload({
url: '/api/newart/',
data: {
username: $scope.username,
email: $scope.email,
comment: $scope.comment,
file: file
}
});
}
}]);
Server:
var nodemailer = require('nodemailer');
var multipartyMiddleware = require('connect-multiparty')();
// multiparty is required to be able to access req.body.files !
app.mailTransporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: ...
pass: ...
},
tls: { rejectUnauthorized: false } // needed or Gmail might block your mails
});
app.post('/api/newart', multipartyMiddleware,function(req,res){
console.log(req.files);
mailOptions = {
from: req.body.email,
to: ...,
subject: ...
text: ...,
attachments: [{
filename: req.files.file.name,
path: req.files.file.path // 'path' will stream from the corresponding path
}]
};
app.mailTransporter.sendMail(mailOptions, function(err) {
if (err) {
console.log(err);
res.status(500).end();
}
console.log('Mail sent successfully');
res.status(200).end()
});
});
The nodemailer examples helped me figure this out!
This works for any file type. The key aspect that some people might miss out is that you need multiparty to access the uploaded file (in req.body.files). Then the most convenient way to attach it is using the path key in the attachment object.
Definitely you can send images as attachment using nodemailer.
Try this for sending image as an attachment :
var mailOptions = {
...
html: 'Embedded image: <img src="cid:unique#kreata.ee"/>',
attachments: [{
filename: 'image.png',
path: '/path/to/file',
cid: 'unique#kreata.ee' //same cid value as in the html img src
}]
}
For more reference on sending image as attachment go through nodemailer's "using Embedded documentation".
For the first part of the question:
Yes! you can send other text data along with image using ng-file-upload. It depends how you want to do it and what you want to achieve.
For example, see the code below:
HTML Template
<form name="form">
<input type="text" ng-model="name" ng-required="true">
<input type="text" ng-model="phoneNo" ng-required="true">
<div class="button" ngf-select ng-model="file" name="file" ngf-pattern="'image/*'" ngf-accept="'image/*'" ngf-max-size="20MB" ngf-min-height="100" ngf-resize="{width: 100, height: 100}">Select</div>
<button type="submit" ng-click="submit()">submit</button>
</form>
Controller
$scope.submit = function() {
if ($scope.form.file.$valid && $scope.file) {
$scope.upload($scope.file);
}
};
// upload on file select or drop
$scope.upload = function (file) {
Upload.upload({
url: 'upload/url',
data: {file: file, 'name': $scope.name, 'phoneNo' : $scope.phoneNo}
}).then(function (resp) {
console.log('Success ' + resp.config.data.file.name + 'uploaded. Response: ' + resp.data);
}, function (resp) {
console.log('Error status: ' + resp.status);
}, function (evt) {
var progressPercentage = parseInt(100.0 * evt.loaded / evt.total);
console.log('progress: ' + progressPercentage + '% ' + evt.config.data.file.name);
});
};
Read ng-file-upload documentation completely to see understand all the things you can do along with file upload. It has many examples to make you understand everything.
I hope it helps, and answer your question.

How to return an image from GridFS in a JSON object (or similarly convenient format)?

I have a form that allows a user to upload an image to GridFS asynchronously.
I'd like to be able to get the image back from the sever so that I can add it to a div via jQuery.
Previously, in other areas of the app, I've been using getJSON() requests that return content from the server in JSON format with:
Bottle
response.content_type = 'application/json'
return dumps(results)
And then accessing individual fields in jQuery with:
HTML
$("#my_content").append(results.my_db_key)
Is it possible to return an image back in a similarly convenient format that is easy to reference and manipulate in jQuery?
As stated, I'd like to be able to update a div with the retrieved image.
Working Code Below - Just need help with the Bottle part
Form
<form id="ajaxUploadForm" enctype="multipart/form-data" method="post" action="/upload">
<input type="file" id="my_img_upload_input" name="my_image">
<input type="submit" value="upload">
</form>
jQuery
$(document).on("click","#ajaxUploadForm input[type=submit]", function (e) {
e.preventDefault();
var myShinyData = new FormData($("#ajaxUploadForm")[0]);
$.ajax({
url: '/upload',
data: myShinyData,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert("This is a success message");
}
});
});
Bottle Route
#route('/upload', method='POST')
def do_upload():
uploaded_image = request.files.my_image
name, ext = os.path.splitext(uploaded_image.filename)
if ext not in ('.png','.jpg','.jpeg'):
return "File extension not allowed."
if uploaded_image and uploaded_image.file:
raw = uploaded_image.file.read()
filename = uploaded_image.filename
dbname = 'grid_files'
db = connection[dbname]
fs = gridfs.GridFS(db)
fs.put(raw,filename=filename)
thing = fs.get_last_version(filename=filename)
# somehow return the image in a convenient format
# that can be referenced in jQuery.
# response.content_type = 'image/jpeg' OR
# response.content_type = 'application/json' OR
# something else?
# return thing
return "You missed a field."
Edit:
Here is one solution - using the base64 encoding approach:
dbname = 'grid_files'
db = connection[dbname]
fs = gridfs.GridFS(db)
filename = "my_image.jpg"
my_image_file = fs.get_last_version(filename=filename)
encoded_img_file = base64.b64encode(my_image_file.read())
return encoded_img_file
Accessed on the front end with:
$("#my_img").attr("src", "data:image/png;base64," + data);
from https://stackoverflow.com/a/21213523/1063287

how to handle multipart/form-data in node.js

I am uploading image file from client side using multipart form data. I want to receieve and write it as a file in the server side using node.js.
<html>
<body>
<form action="url" method="post" enctype="multipart/form-data">
<input type="text" name="imageName">
<input type="file" name="sam">
</form>
</body>
</html>
This is my client side code. How to handle this file in server side.
It is repeated question below link.
Uploading images using Node.js, Express, and Mongoose
Here is example:
// Expose modules in ./support for demo purposes
require.paths.unshift(__dirname + '/../../support');
/**
* Module dependencies.
*/
var express = require('../../lib/express')
, form = require('connect-form');
var app = express.createServer(
// connect-form (http://github.com/visionmedia/connect-form)
// middleware uses the formidable middleware to parse urlencoded
// and multipart form data
form({ keepExtensions: true })
);
app.get('/', function(req, res){
res.send('<form method="post" enctype="multipart/form-data">'
+ '<p>Image: <input type="file" name="image" /></p>'
+ '<p><input type="submit" value="Upload" /></p>'
+ '</form>');
});
app.post('/', function(req, res, next){
// connect-form adds the req.form object
// we can (optionally) define onComplete, passing
// the exception (if any) fields parsed, and files parsed
req.form.complete(function(err, fields, files){
if (err) {
next(err);
} else {
console.log('\nuploaded %s to %s'
, files.image.filename
, files.image.path);
res.redirect('back');
}
});
// We can add listeners for several form
// events such as "progress"
req.form.on('progress', function(bytesReceived, bytesExpected){
var percent = (bytesReceived / bytesExpected * 100) | 0;
process.stdout.write('Uploading: %' + percent + '\r');
});
});
app.listen(3000);
console.log('Express app started on port 3000');
If your question is not solve then please visit this link . This is a nice article about file uploading.
You can use request module for sending a multipart request. Here is the sample code:
var jsonUpload = { };
var formData = {
'file': fs.createReadStream(fileName),
'jsonUpload': JSON.stringify(jsonUpload)
};
var uploadOptions = {
"url": "https://upload/url",
"method": "POST",
"headers": {
"Authorization": "Bearer " + accessToken
},
"formData": formData
}
var req = request(uploadOptions, function(err, resp, body) {
if (err) {
console.log('Error ', err);
} else {
console.log('upload successful', body)
}
});