'upload image to node js server + javascript and display in the same page with ajax jquery
I need to upload a image(jpg||png||jpeg) to the server I created with node js.
I have the router and the requestHandlers.. that redirect to this function:
function reqUpload(request, response) {
var form = new formidable.IncomingForm();
form.parse(request, function (error, fields, files) {
lastFileUploaded=files.up.originalFilename;
if (files.up.originalFilename.match(/\.(jpg|jpeg|png)$/i)) {
//check if alredy exists
fs.access(files.up.originalFilename, fs.F_OK, (err) => {
if (err) {
fs.rename(files.up.filepath, files.up.originalFilename, function (err) {
if (err) {
fs.unlink(files.up.originalFilename);
fs.rename(files.up.filepath, files.up.originalFilename);
}
var data;
fs.readFile('./html/std.html', 'utf8', function (err, data) {
if (err) {
console.error(err);
return
}
response.writeHead(200, { "Content-Type": "text/html" });
response.write(data);
response.end();
});
})
}else{
console.log("Already exists, replacing it!");
fs.rename(files.up.filepath, files.up.originalFilename, function (err) {
if (err) {
fs.unlink(files.up.originalFilename);
fs.rename(files.up.filepath, files.up.originalFilename);
}
})}
});
} else {
console.log("format not accepted! try again.");
}
This is working if I upload my file via a button and the form action ="/reqUpload" however, I need to load in the same page.
How do I do it with ajax + jquery?
I need to display the image uploaded in the same page I uploaded it, without refreshing the page.
I have this function:
function loadPhoto(e){
alert("entered")
var xhr = new XMLHttpRequest();
xhr.open('POST', '/reqUpload');
xhr.onload = function(){
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
alert(this.responseText)
document.getElementById('#photo').innerHTML = this.responseText;
}
xhr.send('/html/std.html');
e.preventDefault();
}
but it breaks and returns this: enter image description here
seems not to send the file in the correct format, or smth like that
Solution 1:[1]
This resolved my case
function loadPhoto(e){
e.preventDefault();
//forming images
var formData = new FormData( document.getElementById("uploading") );
for(var i = 0; i < document.getElementById("up").files.length; i++) {
console.log(i)
formData.append("up[]",document.getElementById("up").files[i]);
}
var filename = document.getElementById('up');
alert(filename)
filename = filename.files[0].name;
alert(filename)
var xhr = new XMLHttpRequest();
xhr.open('POST', '/reqUpload');
xhr.onload = function(){
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
alert(this.responseText)
document.getElementById('#photo').innerHTML = this.responseText;
}
xhr.send(formData);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Ricardo Jacobsen |
