I am building a web app which need to upload a test report. i am working on front end and other guy is working on backend(with nodejs and mongodb). His api server is running separately and my webapp is running separately. now i need to send the uploaded file to his api as it is. i am having a problem in doing it. I am sending data through ajax. this is my ajax code
var $form = $(e.target);
var formData = new FormData();
formData.append('productsfile', $('#prdcttestfile')[0].files[0]);
formData.append('productid', $('#prdctid').val());
formData.append('warantydays', $('#prdctwarranty').val());
formData.append('baseprice', $('#prdctbaseprice').val());
formData.append('discountedpercent', $('#prdctdiscountedprice').val());
formData.append('taxpercent', $('#prdcttax').val());
formData.append('language', $('#prdctlanguage').val());
formData.append('inventoryid', $('#village').val());
$.ajax({
url: '/product/movetoinventory',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function (response) {
if (response.success) {
new PNotify({
title: "Enquiry Updted",
type: "info",
text: "Your enquiry has been updated",
nonblock: {
nonblock: true
},
addclass: 'dark',
styling: 'bootstrap3',
hide: true,
before_close: function (PNotify) {
PNotify.update({
title: PNotify.options.title + " - Enjoy your Stay",
before_close: null
});
PNotify.queueRemove();
return false;
}
});
$('.modal.in').modal('hide');
$("#inventory_product")[0].reset();
}
}
});
when i use console.log(req.body) in my routes i am getting the data along with the FILE PATH(not file). if i use console.log(req.files) i am getting empty {}.
You can use two methods for file uploading.
Send Base64 of the file to the backend.The Backend developer store this file in server and URL of the store location will store in the database.
For node have multer and connect-multiparty npm.You can choose one of them.
For backend code is
var express = require('express'),
bodyParser = require('body-parser'),
host = '127.0.0.1',
port = '3002',
multer = require('multer'),
app = express();
var upload = multer()
app.use(bodyParser.urlencoded({
extended: false
}))
app.post('/file-upload', upload, function(req, res) {
console.log('file upload');
})
app.listen(port, function() {
console.log('hi server run' + " " + port);
})
and the froent-end code is
<body>
<form method="post" enctype="multipart/form-data" action="http://localhost:3002/file-upload">
<input type="file" name="thumbnail">
<input type="submit">
</form>
I think that the a second option is a good option for file upload.You can check multer
for multiple file upload at a
Related
This may be duplicate but I can't solve it.
I can send multiple images by JQuery/Ajax to my server (Asp.Net Core) and save them successfully. But the problem is when I want to add the second batch files, the first batch will not append to form data. I add images with a button and not by input type="file" field.
HTML:
<form asp-area="User" asp-controller="Item" asp-action="Create" id="createForm" method="post" enctype="multipart/form-data" >
<input asp-for="ImageUrl" id="myInput" type="file" name="inputFile[]" accept="image/*" multiple style="display:none" />
<button id="myButton" type="button">+ Add Files</button>
JS:
$(document).ready(function () {
var inputFile = $('#myInput');
$('#myButton').click(function () {
$('#myInput').click();
});
var files = [];
$('#myInput').change(function () {
var newFiles = [];
for (var index = 0; index < inputFile[0].files.length; index++)
{
let file = inputFile[0].files[index];
files.push(file);
}
});
});
$("#createForm").submit(function (e) {
e.preventDefault();
var formData = new FormData(document.getElementById('createForm'));
//var formData = new FormData(this);
files.forEach(file => {
formData.append('file[]', file);
});
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
$.ajax({
type: "POST",
cache: false,
processData: false,
contentType: false,
url: $("#createForm").attr('action'),
enctype: 'multipart/form-data',
data: new FormData(this),
});
});
});
Suppose I choose pictures 1,2,3 and submit my form and all 3 pictures save to server side successfully. Now let's try a new record: I add pictures 1,2,3, after that I choose pictures 4,5,6 so I expect to 6 images to be appended to form data. But only the last selection 4,5,6 are saved to server !
This is my console report in below.As you can see I have input-File[]=3 !! Something like I have no jquery and no ajax and just using pure HTML/Input Multiple file and I can upload only my last selections !!
But when I refresh my page and choose just 1,2,3 images (one selection only), I have input-File[]=3 and file[], [object File]=3 and every thing is good.
I tried data: new FormData() and data: formData and many other options on data parameter but no one could solve my problem :(
Update : ******************************:
Case 1:
var formData = new FormData(document.getElementById('createForm'));
. . .
data: formData,
Results: No image save in server and ImageUrl is null in database.
Case 2:
var formData = new FormData()
. . .
data: formData,
Results in error in console : XML Parsing Error: no root element found
Case 3:
var formData = new FormData(this)
. . .
data: formData,
Results : suppose I select images 1,2,3 at first and then select images 4,5,6. I have images 1,2,3,4,5,6 saved on server and 4,5,6 save twice !! I'm getting near but still can't manage it.
.
I think there might be an error in the way that you copied your code. There is an extra }); after $('#myInput').change(function () { ... });
I'm assuming that is not part of the issue and was just a mistake in pasting it over.
The issue I think is that you were trying to send the files over separately from the inputFiles. Updating the for loop in the submit event handler should give you what you are wanting.
$("#createForm").submit(function (e) {
e.preventDefault();
var formData = new FormData();
files.forEach((file) => {
formData.append('inputFile[]', file);
});
for (var pair of formData.entries()) {
console.log(pair[0] + ', ' + pair[1]);
}
$.ajax({
type: "POST",
cache: false,
processData: false,
contentType: false,
url: $("#createForm").attr('action'),
enctype: 'multipart/form-data',
data: formData,
});
});
Hello I have one registration form of users as soon as user register in next browser tab i will get that registered user details without page refresh for this i got code from github project and tested that which is working perfectly and I have loaded jquery,socket.js file in both pages (data post,retrieving page)as they mentioned in that still i am not getting latest registered users without page refresh ,so please tell me where the code need to be correct.below is my code
code to post data(register users)
$("#submit").click(function(event){
event.preventDefault();
var dataString = {
name : $("#name").val(),
email : $("#wickets").val()
};
$.ajax({
url: "<?= base_url('User/register') ?>",
type: "POST",
data: dataString,
dataType: "json",
cache : false,
success: function (data) {
if (data.success == true) {
var socket = io.connect( 'http://'+window.location.hostname +':3000' );
socket.emit('registered_users', {
name: data.name,
email: data.email
});
}
}, error: function (xhr, status, error) {
alert(error);
},
});
});
code to get name and email of user who have just register by socket
html div tags to print user name and email
<div id="user_name"></div>
<div id="user_email"></div>
script for socket
var socket = io.connect( 'http://'+window.location.hostname+':3000' );
socket.on( 'registered_users', function( data ) {
$( "#user_name" ).prepend( data.name );
$( "#user_email" ).prepend( data.email );
});
I read this: https://github.com/enyo/dropzone/wiki/Set-URL-dynamically but i dont got success... :(
I have 1 form...
And i send the inputs with ajax.
The ajax returns the new id of user. in this moment i want to change de url dropzone for to set path to id of the new user.
$.ajax({
type: "POST",
url: "class/inserir.php?funcao=teste",
data: formdata,
dataType: "json",
success: function(json){
if(json.sucesso=="sim"){
alert("Wait! Sending Pictures.");
this.options.url = "class/upload_img.php?"+json.id;
myDropzone.processQueue();
}else{
location.href="home.php?ir=cad_animal&cad=nao&erro="+json.erro;
}
}
});
var myDropzone = new Dropzone("#imagens", {
url: "class/upload_imgteste.php",
paramName: "file", // The name that will be used to transfer the file
maxFilesize: 1, // MB
addRemoveLinks : true,
dictResponseError: "Não foi possível enviar o arquivo!",
autoProcessQueue: false,
thumbnailWidth: 138,
thumbnailHeight: 120,
});
sorry for my bad english!
Thanks for all.
You may add a function on dropzone's "processing" event listener.
Dropzone.options.myDropzone = {
init: function() {
this.on("processing", function(file) {
this.options.url = "/some-other-url";
});
}
};
Here is the link where I got the code and it works for me: https://github.com/enyo/dropzone/wiki/Set-URL-dynamically
change this
this.options.url = "class/upload_img.php?"+json.id;
to this
myDropzone.options.url = "class/upload_img.php?"+json.id;
Does that work?
New answer for an old question only because I found this answer and the link to the dropzone wiki and didn't like it. Modifying the options of the plugin multiple times like that seems very wrong.
When dropzone uses some options it runs it through a resolveOption function passing in a files array. In the current branch you can define a function for the options: method, url and timeout.
Here's a complete working example including delaying for the ajax:
Dropzone.autoDiscover = false;
const doStuffAsync = (file, done) => {
fetch('https://httpbin.org/get').then((response) => {
file.dynamicUploadUrl = `https://This-URL-will-be-different-for-every-file${Math.random()}`
done();//call the dropzone done
})
}
const getMeSomeUrl = (files) => {
return `${files[0].dynamicUploadUrl}?sugar&spice`;
}
let myDropzone = new Dropzone("#my-awesome-dropzone", {
method: "put",
accept: doStuffAsync,
url: getMeSomeUrl
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.4.0/min/dropzone.min.css">
<form action="/file-upload" class="dropzone" id="my-awesome-dropzone">
</form>
If you need to change the URL dropzone posts to dynamically for each file, you can use the processingfile event and change the options.url.
<form id="my-dropzone" action="/some-url" class="dropzone"></form>
<script>
Dropzone.options.myDropzone = {
init: function() {
this.on("processing", function(file) {
this.options.url = "/some-other-url";
});
}
};
</script>
Another way that worked for me (accept event callback):
$('div#dropzone').dropzone({
options...,
accept: function (file, done) {
this.options.url = 'the url you want';
}
});
BlueWater86's answer didn't work for me. But I agree that changing myDropzone.options.url each time is bad practice, and it actually doesn't work if you are dragging a lot of files into the uploader at the same time.
I wrote the following code and it works well for uploading one file at time and for many at a time. I'm using Backblaze B2 but it should also work for S3.
myDropzone.on('addedfile', function(file) {
options = {
filename: file.name,
type: file.type,
_: Date.now()
};
// Make the request for the presigned Backblaze B2 information, then attach it
$.ajax({
url: '/presign_b2',
data: options,
type: 'GET',
success: function(response){
file.dynamicUrl = response['url'];
myDropzone.enqueueFile(file);
}
});
});
myDropzone.on('sending', function(file, xhr) {
xhr.open("PUT", file.dynamicUrl); // update the URL of the request here
var _send = xhr.send;
xhr.send = function() {
_send.call(xhr, file);
}
});
I am trying to create simple NodeJS server using express framework.
and at client site, I wanted to fetch data using ajax call but it's not working
My Server side code
var express = require('express');
var app = express();
function sendJson(req, res){
console.log('User connected');
var jsonEx = '{ "result" :{"name" : "sachin", "surname" : "Tendulkar"}}';
res.type('application/json');
res.send(JSON.stringify(jsonEx));
}
app.use("/",express.static(__dirname));
app.get("/",sendJson);
app.listen(3000);
And client side code : which is the file index.html
$(document).ready(function(){
//Make ajax call to fetch data
$.ajax({
url: "http://localhost:3000/",
type: "GET",
dataType: 'json',
success: function(resp){
console.log(resp);
console.log("Hello");
}
});
});
but nothing happens after running the example.
console shows no data.
I enter below url in browser to run this
http://localhost:3000/index.html
what is problem with the code ?
Thank you,
Sachin
Express's app.use and app.get will act the same if you specify a path, but will resolve in order. So in this case, all your requests are rendering the index page. See this post(Routing with express.js - Cannot GET Error) Try changing the json data to another route like this:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//Make ajax call to fetch data
$.ajax({
url: "http://localhost:3000/data",
type: "GET",
dataType: 'json',
success: function(resp){
console.log(resp);
console.log("Hello");
}
});
});
</script>
</head>
</html>
and
var express = require('express');
var app = express();
function sendJson(req, res){
console.log('User connected');
var jsonEx = '{ "result" :{"name" : "sachin", "surname" : "Tendulkar"}}';
res.type('application/json');
res.send(JSON.stringify(jsonEx));
}
app.use("/",express.static(__dirname));
app.get("/data",sendJson); // defining data as the get endpoint instead of root
app.listen(3000);
I am developing a mobile site using asp.net and jquery. no plugin. just simple jquery.I am using the
<input type="file"/>
of HTML5.
So few questions to get the big picture:
1.Can i load files without jquery plugin, but only simple jquery? Just picking the file, send it using ajax and catch it on server side?
2. I have noticed the Request.Files attribute of the Request object. Will it get filled only with post of the whole page or can i get my files there using Ajax?
3.In case the answer in 2 is "No!", how do i exclude the files data on the server side?
Thanks
This is the solution i have found:
JS:
<script type="text/javascript">
$(document).ready(function () {
$('#inputFile').on('change', function () {
var file = this.files[0];
var name = file.name;
var size = file.size;
var type = file.type;
var formData = new FormData();
formData.append(file.name, file)
$.ajax({
url: 'AjaxPage.aspx',
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: formData,
type: 'post',
success: function (response) {
alert(response);
},
error: function (e) {
alert(e);
}
});
});
});
</script>
CS: (On ajax page to catch the files and manipulate them as you will)
var files = Request.Files;
HTML:
<body>
<div>
<input type="file" id="inputFile" />
</div>
</body>