I am using nodeJS and I would like to upload a file to the server.
I have pug page where the user fill all the information and choose a file with filechooser. Then I want to send all the information on the page to the server. Therefore, I am using ajax to send a json object and given that file object can not be send through a json object I convert the File object to a json object like this:
function uploadGenome() {
var file = $(':file')[0].files[0];
var fileObject = {
'lastMod': file.lastModified,
'lastModDate': file.lastModifiedDate,
'name': file.name,
'size': file.size,
'type': file.type
};
return fileObject;
}
Then I add everything in a Json object:
var data = {};
data.file = uploadGenome();
data.name = inputs[0].value;
data.description = inputs[1].value;
data.start = inputs[3].value;
data.end = inputs[4].value;
And finally, I send everything with ajax:
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json',
url: url,
success: function (data) {
console.log('success');
console.log(JSON.stringify(data));
if (data === 'done')
{
window.location.href = "/";
} else {
alert('Error Creating the Instance');
}
},
error: function () {
console.log('process error');
}
});
On the server side with NodeJS I get everything, but now how could I copy the file that I get in data.file on the server ? I mean create a copy on the project folder which is on a server.
Related
I need to send mail to user after downloading .csv file. I am not sure how to set callback function after file gets downloaded.
$.ajax({
url: '#Url.Action("GetAllCustomer", "Customers")',
type: 'POST',
data: { 'customerIds': strCustomerId },
success: function (result) {
if (result == "Success") {
location.href = '#Url.Action("DownloadFile", "Customers", new { extension = "csv"})';
} else {
toastLast = toastr.error("No data found", "Generating File");
}
}
});
In above code in first call i am getting all the customers. On success callback i am calling DownloadFile method to download csv file. i have requirement to send mail after downloading file but i am not sure how will i know that file is downloaded. Or Can I achieve with some other way.
Please find my DownloadFile method of controller as below.
public ActionResult DownloadFile(string extension)
{
var dateTime = DateTime.Now.ToString("M.dd.yy");
var fileName = dateTime + " Application File." + extension;
var array = TempData["Output"] as byte[];
if (array != null)
{
var file = File(array, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
return file;
}
else
{
return new EmptyResult();
}
}
Don't use this line
location.href = '#Url.Action("DownloadFile", "Customers", new { extension = "csv"})';
Instead use a ajax request to the Action method
$.ajax({
type: "POST",
url: '#Url.Action("DownloadFile", "Customers")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(){
//add your sccuess handlings
}
error: function(){
//handle errors
}
});
I am building a desktop app using electron. I want to keep the list of all the recent files opened, for this I am using jquery ajax. here is my code
// this function is expected to add a file entry to my json file
this.add_recent_file = function(file_id, file_name, date_opened) {
// Execute the ajax command.
$.ajax({
type: 'POST',
url: './data/recent-files.json',
dataType: 'json',
data: {
id: file_id,
name: file_name,
date: date_opened
},
success: function() {
console.log("Success");
}
});
}
and here is my sample json file:
[
{
"id" : "1",
"name": "File.json",
"date": "24-feb-2018"
}
]
the problem is that console says 'Success' but no changes in json file. Reloading the page didn't change anything.
You can use node.js filesystem to write to the json file. check out the following code.
var fs = require('fs');
var $ = require('jquery');
this.add_recent_file = function (object) {
$.ajax({
type: 'GET',
url: './data/recent-files.json',
dataType: 'json',
success: function (files) {
// append the entry to the array.
files[files.length] = object;
// Get JSON string representation of the array.
var str = JSON.stringify(files);
// Now write it to the json file.
fs.writeFileSync(recent_file_url, str);
},
error: function () {
alert('Error updating json file.');
}
});
}
As stated by #Gerrit Luimstra, you need a backend, If you're using PHP, you might use something like this:
data/update.php
<?php
$id = $_POST['id'];
$name = $_POST['name'];
$dateX = $_POST['date'];
//update database code here
Right now you are using AJAX to POST data to a JSON file and hope that this will update the file. This however is not the case.
What you can do instead is use Electron's file system to write changes to the JSON file.
In this case, your function would become something like:
this.add_recent_file = function(file_id, file_name, date_opened) {
// Create the JSON content
var data = {
id: file_id,
name: file_name,
date: date_opened
};
// If you want to prettify the JSON content
data = JSON.stringify(data, null, 2);
// Write it to the file
fs.writeFileSync('../path/to/recent-files.json', data);
}
This however requires you to use the node filesystem package.
I have created a small asp.net web forms application, to manage emails , i have created a little interface contains mandatory information to send a email, like from , to , subject etc. now i want to attach files to the email, i have used asp.net file upload controller to upload files,
and have to attach multiple files,
Now i want to send this details to code behind, so i thought the best way is to use ajax calls , because i don't want to refresh my page, but i can't figure out the way how to send the attached files to the server side,
i have read some articles and they saying i have to use FormData to send the files ,
then i have created a FormData object and appended all the attached files to the object.but how to pass this object to server side,
my js code as below,
function sendEmail() {
var data = new FormData();
var files = $('.attachment');
$.each(files, function (key, value) {
var file = $(value).data('file');
data.append(file.name, file);
});
$.ajax({
url: "OpenJobs.aspx/sendEmail",
type: "POST",
async: false,
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: null,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
}
Any help?
You need to use Generic handler to upload files using ajax, try below code:
function sendEmail() {
var formData = new FormData();
var files = $('.attachment');
$.each(files, function (key, value) {
var file = $(value).data('file');
formData.append(file.name, file);
});
$.ajax({
url: "FileUploadHandler.ashx",
type: "POST",
contentType: false, // Not to set any content header
processData: false, // Not to process data
data: formData,
success: function (result) {
alert(result);
},
error: function (err) {
alert(err.statusText);
}
});
}
Generic handler
<%# WebHandler Language="C#" Class="FileUploadHandler" %>
using System;
using System.Web;
public class FileUploadHandler : IHttpHandler
{
public void ProcessRequest (HttpContext context)
{
if (context.Request.Files.Count > 0)
{
HttpFileCollection files = context.Request.Files;
for (int i = 0; i < files.Count; i++)
{
HttpPostedFile file = files[i];
string fname = context.Server.MapPath("~/uploads/" + file.FileName);
file.SaveAs(fname);
}
context.Response.ContentType = "text/plain";
}
}
}
I am trying to post a .json file as a single document to an ArangoDB collection, from within javascript/ajax.
I can post (to ArangoDB) the .json file using curl, so that works
I can post (to ArangoDB) simple {key: value} pairs using AJAX, so that works, but combining the two seems to be a bridge too far. I have spent a couple of nights trying to get this far, so any help would be hugely appreciated. thanks in advance.
My javascript code looks like this
var database_URL = prompt("Please enter your URL", "http://xxx..xxx.xxxx.:8529/_db/collection_name/_api/document?collection=PA_Users&createCollection=false");
var fd = new FormData();
var selectedFile = document.getElementById('files').files[0];
console.log(selectedFile.name);// this works
fd.append(selectedFile.name,selectedFile);
var settings = {
url : database_URL,
type : "POST",
headers: {
'Authorization': "Basic " + btoa(username1 + ":" + passwrd1)
},
data: fd,
processData: false,
success: function(data) {
// display feedback to user
alert("booyah");
},
error: function(data) {
// display feedback to user
alert("boo hoo");
}
};
$.ajax(settings);
I think you should use /_api/import instead of /_api/document:
HTTP Interface for Bulk Imports
Here is a small working example (without authorization):
$.ajax({
type: "POST",
url:
'/_api/import?type=auto&collection=' +
encodeURIComponent(yourCollectionID) +
'&createCollection=false',
data: file,
processData: false,
contentType: 'json',
dataType: 'json',
complete: function(xhr) {
if (xhr.readyState === 4 && xhr.status === 201) {
callback(false);
} else {
try {
var data = JSON.parse(xhr.responseText);
if (data.errors > 0) {
// error
}
else {
// success
}
}
catch (err) {
console.log(err);
}
}
}
});
}
The api supports a few input formats:
1.) Single document
{name: "Jonny"}
2.) Multiple documents (one doc in each row)
{name: "Jonny"}
{name: "Adam"}
{name: "Peter"}
3.) Multiple documents in JSON array
[{name: "Jonny"}, {name: "Adam"}, {name: "Peter"}]
I'm trying to upload file to the web service using JavaScript and JQuery. My current implementation is working correctly in the local environment.
But after deploying my solution to the server and try to access from outside it's not working and saying server side error occurred. Other thing I found is other web methods of the same web service are working correctly and just this file upload method is not working.
Here is my asp.net web service file upload method.
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public object SaveFile()
{
var bugID = int.Parse(HttpContext.Current.Request.Form["bugID"]);
var fileName = HttpContext.Current.Request.Form["name"];
var fileType = HttpContext.Current.Request.Form["type"];
var file = HttpContext.Current.Request.Files[0];
// file saving logic
// .....
return new JavaScriptSerializer().Serialize(new
{
Message = 1,
Name = fileName,
DocumentID = attach.DocumentID // Saved file ID
});
}
Here is the javascript method I used to upload the file to the web service
function uploadFile() {
var data = new FormData(),
file = $("#fileToUpload")[0].files[0];
data.append("name", file.name);
data.append("size", file.size);
data.append("type", file.type);
data.append("file", file);
data.append("bugID", bugID);
$.ajax(
{
url: baseURL + "Webservice/BugsWebService.asmx/SaveFile",
dataType: "xml",
type: "POST",
data: data,
cache: false,
contentType: false,
processData: false,
success: function (res) {
console.log(res);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
}
In development environment web service url is
http://localhost:55225/Bugs/View.aspx
When host the site url is
http://[ip-address]/Internal/Bugs/View.aspx
This is the error I'm getting when try to upload the file
http://[ip-address]/Internal/Webservice/BugsWebService.asmx/SaveFile
500 (Internal Server Error)
What is the issue with my implementation?