I upload a file in HTML with nodejs module MULTER:
<form enctype = "multipart/form-data"
action = "/upload"
method = "POST">
<input type="file" name="file" >
<p></p>
<input type="submit" value="Upload File" name="submit" class="btn btn-primary">
</form>
<span>{{submit.message}}</span>
I want to show the response message not in on a new page which is now, I want to show it in the message span.
var upload = multer({ storage : storage}).single('file');
router.post('/upload', function(req, res){
upload(req, res, function(err) {
if(err){
return res.status(400).send({
message: 'wrong'
});
console.log("Error: '" + err + "'");
}else{
return res.status(200).send({
message: 'fine'
});
console.log('Uploaded file: ' + req.file.filename);
}
});
});
angularjs:
this.submit = function() {
$http.post("/upload", data)
.then(
function(res) {
console.log("posted successfully");
this.message = "succesful";
},
function(res) {
console.log(res.data.message);
this.message = res.data.message
}
);
}
How can I parse the response message to the html file without opening a new page. I want to show the response message in the html span response.
Does anyone know how to do this?
Related
I use Node.js express + PostgreSQL
How to pass the path to my CSV file through Node.js in a BD query ?
I have and html form which is having file input like -
<form method="post" action="import_csv" target="_blank" enctype="multipart/form-data" >
<p><input type="file" name="csv_file">
<input type="submit" value="submit"></p>
</form>
After, I have redirected this post request to the following method of controller (server).
app.post("/import_csv_file",urlencodedParser,function(req,res) {
var config = {
user:'postgres',
database:'mybd',
password: '1',
host:'localhost',
port:5432,
max:10,
idleTimeoutMillis: 30000
}
var pool = new pg.Pool(config)
pool.connect(function(err, client, done){
console.log("teacher")
if(err){
return console.error('error')
}
file_path = req.body.csv_file
console.log(file_path)
client.query("select * from import_csv($1,$2)",[log2,req.body.csv_file], function(err, result) {
done()
req.session.user2 = result
if (err){
res.end()
return console.error("error")
}
res.render('import_csv_file',{jour:result}})
})
})
The result I am getting here is - undefined (console.log(req.body.csv_file))
How do I pass the path to my CSV file to a database query so that everything works
Thank you all for your help !
installer multer and next
const path = require('path')
var multer = require('multer');
const upload = multer({ dest: '/tmp/' });
app.post("/import_csv_file",upload.any(),function(req,res) {
var config = {
user:'postgres',
database:'mybd',
password: '1',
host:'localhost',
port:5432,
max:10,
idleTimeoutMillis: 30000
}
var pool = new pg.Pool(config)
pool.connect(function(err, client, done){
console.log("teacher")
if(err){
return console.error('error')
}
console.log(req.body);
console.log(req.files);
const file = req.files[0];
console.log(file)
console.log(file.path)
client.query("select * from import_csv($1,$2)",[log2,file.path], function(err, result) {
done()
req.session.user2 = result
if (err){
res.end()
return console.error("error")
}
res.render('import_csv_file',{jour:result}})
})
})
and html
<form method="post" action="inside_teacher_import_ocenka" target="_blank" enctype="multipart/form-data">
<p><input type="file" name="csv_ocenka">
<input type="submit" value="Отправить"></p>
</form>
I have a small HTML template and what I want is to upload image from one location to another. After selecting and clicking on the upload button, response gives me "Uploaded successfully" But the image is not in the destination folder. Please look into the below code.
HTML
<form id="frmUploader" enctype="multipart/form-data" action="book/api/Upload/" method="post">
<input type="file" name="imgUploader" multiple />
<input type="button" name="submit" id="btnSubmit" value="Upload" onclick="upload()"/>
</form>
index.js
function upload() {
axios.post(baseUrlLocal+'/book/api/Upload', {headers: headers})
.then(response => {
console.log(response.data.success)
if (response.data.success) {
console.log("hi: "+response)
// $.notify("New Book is Added to your Library", "success");
}
})
.catch(function (error) {
console.log(error)
// $.notify("Please check all the details","warn");
});
}`
book.js
var Storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, "../public/images/");
},
filename: function(req, file, callback) {
callback(null, file.fieldname + "_" + Date.now() + "_" +
file.originalname);
}
});
var upload = multer({
storage: Storage
}).array("imgUploader", 3);
router.get("/image", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
`router.post("/api/Upload", function(req, res) {
upload(req, res, function(err) {
if (err) {
return res.end("Something went wrong!");
}
return res.end("File uploaded sucessfully!.");
});
});`
My html code is
<form action="/file_upload" method="POST" enctype="multipart/form-data">
<input type="file" name="photos" id="photos" accept='image/*' multiple>
<input type="submit" value="Upload" id="upload_my_photos" disabled>
</form>
In sails I am using
uploadFiles = req.file("photos");
This is only fetching just single file.
Edit : I would also like to save the individual files. Below is the code I am using but no files are getting uploaded:
req.file('photos').upload(function (err, uploadedPhotos) {
if (err) return res.serverError(err);
async.eachSeries(uploadedPhotos,
function (uploadedFile, callback) {
sails.log("upload file size and name is " + uploadedFile.size + " " + uploadedFile.filename);
req.file(uploadedFile).upload({
dirname: "path/to/directory",
// saveAs: function (file, cb) { cb(null, file.filename); }
},
function onUploadComplete(err, files) {
if (err) return res.serverError(err);
if (files.length === 0) {
return res.badRequest('No file was uploaded');
}
sails.log("files uploaded");
});
}, function (err) {
// if any of the saves produced an error, err would equal that error
if (err) {
console.log(err);
} else {
return res.status(200).send({ success: false, message: "failed to upload" });
}
});
});
Sails req.file() is representing an incoming multipart file upload from the specified field.
You need to subscribe to the request with a callback in which the uploaded files will be passed as an second argument:
req.file('photos').upload(function (err, uploadedPhotos){
if (err) return res.serverError(err);
return res.json({
message: uploadedPhotos.length + ' file(s) uploaded successfully!',
files: uploadedPhotos
});
});
I'm getting req.file as undefined. I have tried everything. I have searched for other solutions, but it's not a problem in input name="avatar" attr and upload.single("avatar").
Also, I'm getting an error in the console:
Error for image upload 400 - Bad Request
{"code":"ER_PARSE_ERROR","errno":1064,"sqlMessage":"You have an error
in your SQL syntax; check the manual that corresponds to your MySQL
server version for the right syntax to use near '?)' at line
1","sqlState":"42000","index":0,"sql":"INSERT INTO avatars (image)
VALUES(?)"}
I would say that it is because req.file is undefined.
Please, help me to understand what I'm doing wrong.
api.js:
var storage = multer.diskStorage({
destination: function(req, file, callback) {
callback(null, "./assets/images/uploads");
},
filename: function(req, file, callback) {
callback(null, file.fieldname + "_" + Date.now() + "_" +
file.originalname);
}
});
var upload = multer({
storage: storage,
limits: {fileSize: 1000000},
fileFilter: function(req, file, cb) {
checkFileType(file, cb);
}
});
function checkFileType(file, cb) {
const filetypes = /jpeg|jpg|png|gif/;
const extname = filetypes.test(file.originalname.toLowerCase());
const mimetype = filetypes.test(file.mimetype);
if(extname && mimetype) {
return cb(null, true);
} else {
cb('Error: Images only');
}
}
router.post("/upload", upload.single('avatar'), function(req, res) {
console.log(req.file); // <- ALWAYS UNDEFINED
pool.getConnection(function(err, connection) {
if (err) throw err;
connection.query('INSERT INTO avatars (image) VALUES(?)', req.file,
function (error, results, fields) {
if(error){
console.log("Error: " + error);
res.status(400).send(error);
}
res.status(200).end(JSON.stringify(results));
connection.release();
if (error) throw error;
});
});
});
html:
<form enctype="multipart/form-data">
<input class="form-control"
(change)="onFileSelected($event)"
type="file" name="avatar">
<button type="submit" class="btn btn-danger float-right" (click)="onUpload()">Upload image</button>
</form>
ctrl:
onFileSelected(event) {
if(event.target.files.length > 0) {
this.uploadImage = <File>event.target.files[0];
}
}
onUpload() {
if(this.uploadImage) {
this.friendService.uploadFile(this.uploadImage)
.subscribe(
data => {
return true;
},
error => {
console.error('Error for image upload ' + error);
return false;
})
}
}
service:
uploadFile(file): Observable<any> {
return this.http.post(`${this.apiUrl}/upload`, file)
.map(res => res.json())
.catch(this.handleError);
}
db mysql avatars table:
Field - image
Type - blob
Null - NO
Key Default Extra - Empty
while uploading file it should be form data and content type should be multipart/form-data
For your reference: File Upload In Angular?.
I hope this will help you.
Following is my code for file upload.
<form encType="multipart/form-data" action="">
<input type="file" name="fileName" defaultValue="fileName"></input>
<input type="button" value="upload" onClick={this.handleClick.bind(this)}></input>
</form>
handleClick(){
let deliveryId = this.props.params.deliveryId;
var data = new FormData();
var imagedata = document.querySelector('input[type="file"]').files[0];
data.append("data", imagedata);
console.log('Data', data);
fetch(apiBaseUrl, {
mode: 'no-cors',
method: "POST",
body: JSON.stringify({
'item_file': data,
'delivery_id': deliveryId,
'description': 'test description'
})
}).then(function (res) {
if (res.ok) {
alert("Perfect! ");
} else if (res.status == 401) {
alert("Oops! ");
}
}, function (e) {
alert("Error submitting form!");
});
}
Though, I can see the file details in 'imagedata', 'data' is coming empty. I am not able to figure out why 'data' is empty. That's why the backend call is failing.
Following is the request payload going to the server after submit:
{item_file: {}, delivery_id: "eeb9422e-9805-48eb-a8be-ad2e27f3f643", description: "test description"}
You can use FormData itself to achieve file upload with extra parameters like deliveryId. And you can't stringify the file.
handleClick() {
let deliveryId = this.props.params.deliveryId;
var imagedata = document.querySelector('input[type="file"]').files[0];
var data = new FormData();
data.append("item_file", imagedata);
data.append('delivery_id', deliveryId);
data.append('description', 'test description');
fetch(apiBaseUrl, {
mode: 'no-cors',
method: "POST",
body: data
}).then(function (res) {
if (res.ok) {
alert("Perfect! ");
} else if (res.status == 401) {
alert("Oops! ");
}
}, function (e) {
alert("Error submitting form!");
});
}