How to upload the image in angularjs and mysql and node.js?
<html>
<head>
<script src = "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
</head>
<body ng-app = "myApp">
<div ng-controller = "myCtrl">
<input type = "file" file-model = "myFile"/>
<button ng-click = "uploadFile()">upload me</button>
</div>
<script>
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function(scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function(){
scope.$apply(function(){
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function(file, uploadUrl){
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined}
})
.success(function(){
})
.error(function(){
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function($scope, fileUpload){
$scope.uploadFile = function(){
var file = $scope.myFile;
console.log('file is ' );
console.dir(file);
var uploadUrl = "/fileUpload";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
</body>
</html>
AngularJs is a client side language. so it is not able to direct save data to MySql.
If any data is store in a database or in a server you must used any server side language.
You are create a web service that can tack response from client side (AngularJS) and send proper response.
File Upload in Mysql using NodeJs
fs.open(temp_path, 'r', function (status, fd) {
if (status) {
console.log(status.message);
return;
}
var buffer = new Buffer(getFilesizeInBytes(temp_path));
fs.read(fd, buffer, 0, 100, 0, function (err, num) {
var query = "INSERT INTO `files` SET ?",
values = {
file_type: 'img',
file_size: buffer.length,
file: buffer
};
mySQLconnection.query(query, values, function (er, da) {
if (er)throw er;
});
});
});
function getFilesizeInBytes(filename) {
var stats = fs.statSync(filename)
var fileSizeInBytes = stats["size"]
return fileSizeInBytes
}
Related
I have this HTML (attached).
It is called by a web app that still works on I.E (for at least one or two months) due to some problems we have with the vendor.
The web app calls this HTML and it is opened in I.E also.
I need this HTML to be opened in Chrome.
Is there a way i can do this by adding something to the HTML itself?
<html>
<head>
<script>
async function setSRC(){
try{
var xhr;
const params = new Proxy(new URLSearchParams(window.location.search),
{
get: (searchParams, prop) => searchParams.get(prop),
});
var docId = params.docId;
var url = "``http://wsp-exttest.lcardtest.corp:4440/rest.oms/MaxRestService/getPDF?docId=``" + docId;
let response = await new Promise(resolve => {
xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function(e) {
resolve(xhr.response);
};
xhr.onerror = function () {
resolve(undefined);
console.error("** An error occurred during the XMLHttpRequest");
};
xhr.send();
})
//
var j = JSON.parse(xhr.responseText);
var pdfData = j[0].content;
var letterFrame = document.getElementById("letterFrame");
letterFrame.src = "data:application/pdf;base64," + pdfData;
/*letterFrame.onreadystatechange = () => {
if (letterFrame.readyState === 'complete') {
alert(letterFrame.readyState);
letterFrame.src = "data:application/pdf;base64," + pdfData;
}
};*/
}
catch(e)
{
if(confirm("Load faile: " + e.message + "click ok to retry"))
setSRC();
}
}
</script>
</head>
<body onload="setSRC()">
<iframe id="letterFrame" width="1200px" height="800px" onload=""></iframe>
Reload
</body>
</html>
Reload
My webpage provides functionallity to convert pdf to image.
For Webpage i am using Firebase Hosting and for functions obvs Functions.
But after file upload function logs error in firebase dashboard Boundary not found
Below is the code i used to upload file in html:
function uploadFile() {
var file = document.getElementById("file_input").files[0];
var pass = document.getElementById("pass").value;
console.log(file + pass);
var formdata = new FormData();
formdata.append("file", file);
formdata.append("password", pass);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", "/upload");
ajax.setRequestHeader("Content-Type", "multipart/form-data");
ajax.send(formdata);
}
and this is the code of functions:
var functions = require('firebase-functions');
var process;
var Busboy;
var path = require('path');
var os = require('os');
var fs = require('fs');
exports.upload = functions.https.onRequest((req, res) => {
const busboy = new Busboy({ headers: req.headers });
const fields = {};
const tmpdir = os.tmpdir();
const uploads = {};
const fileWrites = [];
var pass = '';
busboy.on('file', (fieldname, file, filename) => {
console.log(`Processed file ${filename}`);
const filepath = path.join(tmpdir, filename);
uploads[fieldname] = filepath;
const writeStream = fs.createWriteStream(filepath);
file.pipe(writeStream);
const promise = new Promise((resolve, reject) => {
file.on('end', () => {
writeStream.end();
});
writeStream.on('finish', resolve);
writeStream.on('error', reject);
});
fileWrites.push(promise);
});
busboy.on('field', function (fieldname, val, fieldnameTruncated, valTruncated, encoding, mimetype) {
pass = val;
});
busboy.on('finish', function () {
console.log('Done parsing form!');
console.log(pass);
console.log(uploads);
process.processCard(uploads['file'], pass, 2).then((s) => {
res.end(`
<!DOCTYPE html>
<html>
<body>
ImageConverted!!
<img src="data:image/jpeg;base64,${s}" width="90%"></img>
</body>
</html>
`);
}).catch((err) => { res.end('Error: ' + err) });
});
busboy.end(req.body);
});
What am i doing wrong ?
For multipart body it is recommended to use req.rawBody instead of req.body
https://stackoverflow.com/a/48289899/6003934
I am creating a web app in which I am storing user images in my folder, after a while I found an example which helps me,
but I am getting the error
HTTP Error 403.14 - Forbidden The Web server is configured to not list
the contents of this directory.
and my code is
source
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script>
<script src="https://angular-file-upload.appspot.com/js/ng-file-upload-shim.js"></script>
<script src="https://angular-file-upload.appspot.com/js/ng-file-upload.js"></script>
</head>
body
<div ng-app="myApp" ng-controller="myCtrl">
<input type="file" file-model="myFile" />
<button ng-click="uploadFile()">upload me</button>
save
</div>
script
<script>
//inject angular file upload directives and services.
var myApp = angular.module('myApp', []);
myApp.directive('fileModel', ['$parse', function ($parse) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
var model = $parse(attrs.fileModel);
var modelSetter = model.assign;
element.bind('change', function () {
scope.$apply(function () {
modelSetter(scope, element[0].files[0]);
});
});
}
};
}]);
myApp.service('fileUpload', ['$http', function ($http) {
this.uploadFileToUrl = function (file, uploadUrl) {
var fd = new FormData();
fd.append('file', file);
$http.post(uploadUrl, fd, {
transformRequest: angular.identity,
headers: { 'Content-Type': undefined }
})
.success(function () {
})
.error(function () {
});
}
}]);
myApp.controller('myCtrl', ['$scope', 'fileUpload', function ($scope, fileUpload) {
$scope.a = function () {
console.log('called');
}
$scope.uploadFile = function () {
console.log('called');
var file = $scope.myFile;
console.log('file is ');
console.dir(file);
var uploadUrl = "http://localhost:9206//file//";
fileUpload.uploadFileToUrl(file, uploadUrl);
};
}]);
</script>
and the url is
http://localhost:9206//file//
let me explain this
this is my one page application, I want to save image in my folder called file,
when a user uploaded his/her image, the image should be stored in the folder,
but instead of this I am getting this error
(HTTP Error 403.14 - Forbidden)
what I need to do now?
It appears that the problem can be fixed by enabling the IIS. You can enable and configure the Internet Information Service (IIS) on your computer (given that you are using localhost) by following the instructions on this link:
https://msdn.microsoft.com/en-us/library/ms181052(v=vs.80).aspx
It seems that example-template.dust somehow gets cached. The first time running the gulp default task it correctly takes the current version of example-template.dust and renders it correctly in index.html.
But later changes to example-template.dust aren't included in the rendered index.html even though the watch task correctly fires and executes the dust task.
I'm thinking it has to do with some configuration errors.
Here is the gulp tasks and templates. Everything else works.
example-template.dust
Hello, from a template. Rendered with <b>{type}</b>
index.html
<!DOCTYPE html>
<html>
<head>
<title>{name}</title>
<link rel="stylesheet" href="main.css"/>
</head>
<body>
<h1>version \{version}</h1>
<p>
{>example-template type="gulp"/}<br/>
There are special escape tags that you can use to escape a raw { or } in dust.<br/>
{~lb}hello{~rb}
</p>
<script src="main.js"></script>
</body>
</html>
gulp-dust-html task
var gulp = require('gulp');
var dust = require('dustjs-linkedin');
var browserSync = require('browser-sync');
var error = require('./errorHandling.js');
var dusthtml = require('gulp-dust-html');
var config = require('../../config.js');
gulp.task('dust', function () {
return gulp.src(config.build.src+'/**/*.html')
.pipe(dusthtml({
basePath: config.build.src+'/',
data: config.build.data
}))
.on('error', error)
.pipe(gulp.dest(config.build.dev+'/'))
.pipe(browserSync.reload({stream:true}));
});
gulp.task('watch-dust', ['dust'], browserSync.reload);
watch task
var gulp = require('gulp');
var watch = require('gulp-watch');
var reload = require('browser-sync').reload;
var config = require('../../config.js');
gulp.task('watch', function() {
gulp.watch(config.build.src+"/**/*.scss", ['sass', reload]);
gulp.watch(config.build.images, ['images', reload]);
gulp.watch([config.build.src+"/**/*.dust"], ['watch-dust', reload]);
gulp.watch([config.build.src+"/**/*.html"], ['watch-dust', reload]);
});
default gulp task
gulp.task('default', ['browserSync','images', 'iconFont', 'sass', 'js', 'dust', 'watch']);
I'm open for alternative suggestions as well.
Atm I'm thinking it could be an idea to use https://www.npmjs.com/package/gulp-shell and link it to the watch task.
ps: I don't have enough reputation to create a gulp-dust-html tag
As #Interrobang said, dust.config.cache = false solved it.
Here is the updated gulp-dust-html module (not on npm)
'use strict';
var gutil = require('gulp-util');
var path = require('path');
var fs = require('fs');
var through = require('through2');
var dust = require('dustjs-linkedin');
module.exports = function (options) {
if (!options)
options = {}
var basePath = options.basePath || '.';
var data = options.data || {};
var defaultExt = options.defaultExt || '.dust';
var whitespace = options.whitespace || false;
dust.config.cache = options.cache || false; //default cache disabling of templates.
dust.onLoad = function(filePath, callback) {
if(!path.extname(filePath).length)
filePath += defaultExt;
if(filePath.charAt(0) !== "/")
filePath = basePath + "/" + filePath;
fs.readFile(filePath, "utf8", function(err, html) {
if(err) {
console.error("Template " + err.path + " does not exist");
return callback(err);
}
try {
callback(null, html);
} catch(err) {
console.error("Error parsing file", err);
}
});
};
if (whitespace)
dust.optimizers.format = function (ctx, node) { return node; };
return through.obj(function (file, enc, cb) {
if (file.isNull()) {
this.push(file);
return cb();
}
if (file.isStream()) {
this.emit('error', new gutil.PluginError('gulp-dust', 'Streaming not supported'));
return cb();
}
try {
var contextData = typeof data === 'function' ? data(file) : data;
var finalName = typeof name === 'function' && name(file) || file.relative;
var tmpl = dust.compileFn(file.contents.toString(), finalName);
var that = this;
tmpl(contextData, function(err, out){
if (err){
that.emit('error', new gutil.PluginError('gulp-dust', err));
return;
}
file.contents = new Buffer(out);
file.path = gutil.replaceExtension(file.path, '.html');
that.push(file);
cb();
})
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-dust', err));
}
});
};
I have a no of images on page and trying to save it inside IndexDb if it does not exist.
All seems to be working fine and images load up instantly if it exist but looks like browser memory is leaking. It's give some jerk and hang sometime. I m not sure how this can be handle, I have written a directive that looks like this
(function () {
'use strict';
// TODO: replace app with your module name
angular.module('app').directive('imageLocal', imageLocal);
imageLocal.$inject = ['$timeout', '$window', 'config', 'indexDb'];
function imageLocal($timeout, $window, config, indexDb) {
// Usage:
//
// Creates:
//
var directive = {
link: link,
restrict: 'A'
};
return directive;
function link(scope, element, attrs) {
var imageId = attrs.imageLocal;
// Open a transaction to the database
var transaction;
$timeout(function () {
transaction = indexDb.db.transaction(["mystore"], "readwrite");
getImage();
}, 500);
function getImage() {
transaction.objectStore('mystore').get(imageId)
.onsuccess = function (event) {
var imgFile = event.target.result;
if (imgFile == undefined) {
saveToDb(imgFile);
return false;
}
showImage(imgFile);
}
}
function showImage(imgFile) {
console.log('getting');
// Get window.URL object
var url = $window.URL || $window.webkitURL;
// Create and revoke ObjectURL
var imageUrl = url.createObjectURL(imgFile);
element.css({
'background-image': 'url("' + imageUrl + '")',
'background-size': 'cover'
});
}
function saveToDb() {
// Create XHR
var xhr = new XMLHttpRequest(),
blob;
xhr.open("GET", config.remoteServiceName + '/image/' + imageId, true);
// Set the responseType to blob
xhr.responseType = "blob";
xhr.addEventListener("load", function () {
if (xhr.status === 200) {
console.log("Image retrieved");
// Blob as response
blob = xhr.response;
console.log("Blob:" + blob);
// Put the received blob into IndexedDB
putInDb(blob);
}
}, false);
// Send XHR
xhr.send();
function putInDb(blob) {
// Open a transaction to the database
transaction = indexDb.db.transaction(["mystore"], "readwrite");
// Put the blob into the database
var request = transaction.objectStore("mystore").add(blob, imageId);
getImage();
request.onsuccess = function (event) {
console.log('saved');
}
};
}
}
}
})();