failed uploading file using Express4 and multer - ajax

I am trying to do the image ajax upload using Express4 and multer, but it doesn't work
here is my request screenshot
and here is the server script
var multer = require('multer');
var upload = multer({ dest: 'uploads/' });
var router = express.Router();
router.route('/upload')
.post(upload.single('file'), function(req, res) {
console.log(req.file);
//req.file is undefined
});
updated client code:
import Ember from 'ember';
export default Ember.TextField.extend({
type: 'file',
change: function(e) {
var inputFiles = e.target.files;
var inputFile = inputFiles[0];
var formData = new FormData();
formData.append('file', inputFile);
Ember.$.ajax({
type: 'POST',
url: '/upload',
data: formData,
cache: false,
contentType: false,
processData: false,
success: function(data) {
console.log(data);
},
error: function(err) {
console.error(err)
}
})
}
});

Related

merge ajaxform with ajax to upload image

I try to create upload photos in my nodejs site.
I used this code to choose file and upload the image:
var fileData = null;
function loadFile() {
var preview = document.querySelector('file');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
fileData = file;
}
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile() {
data = new FormData();
data.append('file', fileData);
$.ajax({
url: "/post_pdf/",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
document.getElementById("result").innerHTML = 'Result: Upload successful';
},
error: function(e) {
document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
}
});
}
With loadfile funcion i choose my image, and with Uploadfile function i upload the image with ajax.
if i use it alone its work perfect and upload the image to the location.
but when i try to add this code to my code, it make alot of errors.
in my code i send to back end all the forms in the pug file:
$('#account-form').ajaxForm({
error : function(e){
if (e.responseText == 'title-empty'){
av.showInvalidTitle();
}
},
success : function(responseText, status, xhr, $form){
if (status == 'success')
{
$('.modal-alert').modal('show');
console.log(responseText)
}}
});
i try to merge the ajaxform with the ajax but when i merege the formdata or i send in ajaxform the data of the file is send error.
how can i merge the codes?
thanks for helping.
Try to submit form it will submit form with your image.
let form = $("#form_id");
$.ajax({
url : $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
success:function(data){
},
error: function (xhr, status, e) {
}
});
#Yogesh Patel
when i use this code:
$('#account-form-btn2').on('click', function(e) {
let form = $("#account-form");
$.ajax({
url: $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
error: function (e) {
if (e.responseText == 'title-empty') {
av.showInvalidTitle();
}
},
success: function (responseText, status, xhr, $form) {
if (status == 'success') {
$('.modal-alert').modal('show');
}
}
});
});
for some reason it sends the values to "routes" three times.
and it doesn't catch the erorrs or success.
and it sends me to a white window with the value of the callback.
if needed, i can send the function that gets the values and returns them (app.post).

File upload using jquery/ajax for REST API

I was trying to upload file to a remote server using REST api by ajax/jquery with the following script, but it returns 400 error with a Bad request. I have tested the end point with curl, which is giving correct response and file is being uploaded.
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
fire_ajax_submit();
});
});
function fire_ajax_submit() {
// Get form
var form = $('#fileUploadForm')[0];
alert(form.files[0]);
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "http://10.13.20.166:5332/fileUploadtoFolder",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
}
Change your code 👇
var data = new FormData(form);
Use this code 👇
// Create an FormData object
var data = new FormData(document.getElementById("fileUploadForm"));
Try again

ajax error 500 (Internal Server Error)

i used ajax to pass data form to laravel controller
But when i run my code , it alway return error (Internal Server Error)
$(document).ready(function() {
$("#btnSave").click(function(e){
var _token = $("input[name='_token']").val();
// var selPartners = $("input[name='selPartners'] option:selected").val();
var selPartners= $('#selPartners :selected').text();
var txtDescription = $("input[name='txtDescription'] ").val();
var txtPrice = $("input[name='txtPrice']").val();
var txtWarrantyDate = $("input[name='txtWarrantyDate']").val();
var itemImage = $('#itemImage').prop('files')[0];
// var selItems =$("input[name='selItems']").val();
var selItems= $('#selItems :selected').text();
var x ={_token:_token, selPartners:selPartners, selItems:selItems, txtDescription:txtDescription, txtPrice:txtPrice, txtWarrantyDate:txtWarrantyDate, itemImage:itemImage}
// console.log(x);
$.ajax({
url: "/additem",
type:'POST',
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: {_token:_token, selPartners:selPartners, selItems:selItems, txtDescription:txtDescription, txtPrice:txtPrice, txtWarrantyDate:txtWarrantyDate, itemImage:itemImage},
success: function(data) {
if($.isEmptyObject(data.error)){
console.log('ok');
}else{
console.log('failed');
}
}
});
});
});
At controller just has:
return response()->json(['error'=>'failed']);

Jquery Upload with Progressbar

I have an Ajax-Upload script that works fine. Now I want add an progressbar or something else. How can I implement something like that in my script below:
$('body').on('change', '#uploadFile', function() {
// Post-Data
var data = new FormData();
data.append('file', this.files[0]);
data.append('uid', $("#uploadFile").attr('data-uid'));
// Ajax-Call
$.ajax({
url: "uploadUserpic.php",
data: data,
type: "POST",
processData: false,
contentType: false,
success : handleData
});
});
function handleData(data) {
$("#messagePic").html(data);
//do some stuff
}
Not possible with $.ajax, You need a XMLHttpRequest object.
Try this:
var data = [];
$.ajax({
xhr: function () {
var xhr = new window.XMLHttpRequest();
// For Upload
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
}
}, false);
// For Download
xhr.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total;
}
}, false);
return xhr;
},
type: 'POST',
url: "/echo/html",
data: data,
success: function (data) {}
});
http://jsfiddle.net/GvdSy/

File not getting uploaded at server

I am getting this following error. i am trying to upload the file to the server.can somebody please suggest something
Error - Failed to load resources: The server responded with a status of 405 method not allowed
</article>
<script>
function sendFileToServer(formData,status)
{
var uploadURL ="http://localhost/upfile/file/"; //Upload URL
var extraData ={}; //Extra Data.
var jqXHR=$.ajax({
xhr: function() {
var xhrobj = $.ajaxSettings.xhr();
if (xhrobj.upload) {
xhrobj.upload.addEventListener('progress', function(event) {
var percent = 0;
var position = event.loaded || event.position;
var total = event.total;
if (event.lengthComputable) {
percent = Math.ceil(position / total * 100);
}
//Set progress
status.setProgress(percent);
}, false);
}
return xhrobj;
},
url: uploadURL,
type: "POST",
contentType:false,
processData: false,
cache: false,
data: formData,
success: function(data){
status.setProgress(100);
$("#status1").append("File upload Done<br>");
}
});
status.setAbort(jqXHR);
}
contentType: 'multipart/form-data',
processData: false,
type: 'POST'
make sure you check your contentType

Resources