im doing simple file uploader to apps script but I faced some troubles with uploading data as file. Lets say I have this code:
function doPost(e) {
console.log(e)
}
and I do a simple POST request in node.js
let formData = {
theFile: {
value: fs.createReadStream('myawersome.file'),
options: {
filename: 'myawersome.file',
contentType: 'some/mimetype'
}
}
}
let params = {
url: 'my-script-url',
followAllRedirects: true,
formData: formData
}
request.post(params)
So, whats the problem. I dont see any files in my e param in doPost. That is my console.log output
{"queryString":"","parameter":{},"contextPath":"","parameters":{},"contentLength":9483}
I can see that I have some data in request, but everything is empty. e.parameters.theFile and e.theFile are undefined. Where is my file?
the call of createReadStream just create the stream but don't read the file
to read the file, try that :
var rs = fs.createReadStream('myawersome.file');
rs.on("data", function (chunk) {
var content = chunk.toString();
var formData = {
theFile: {
value: content,
options: {
filename: 'myawersome.file',
contentType: 'some/mimetype'
}
}
}
var params = {
url: 'my-script-url',
followAllRedirects: true,
formData: formData
}
request.post(params)
});
rs.resume(); // this launches the read
Related
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.
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.
Here i have a form in which i have a input type file to upload my file when the upload button is click i need to post the multipart/form-data to web api
where i upload the file to Minio Server.I have pasted the javascript and web api i use below.
When i press upload button after i get 500 (Internal Server Error).Help me with suggestions.
$("#upload").click(function () {
var file = new FormData($('#uploadform')[0]);
file.append('tax_file', $('input[type=file]')[0].files[0]);
$.ajax({
type: "POST",
url: 'http://localhost:53094/api/values',
data: file,
//use contentType, processData for sure.
contentType: "multipart/form-data",
processData: false,
beforeSend: function () {},
success: function (msg) {
$(".modal .ajax_data").html("<pre>" + msg +
"</pre>");
$('#close').hide();
},
error: function () {
$(".modal .ajax_data").html(
"<pre>Sorry! Couldn't process your request.</pre>"
);
$('#done').hide();
}
});
});
[HttpPost]
public string Post(IFormFile file)
{
try
{
var stream = file.OpenReadStream();
var name = file.FileName;
minio.PutObjectAsync("student-maarklist", "sample.jpeg", stream, file.Length);
return "Success";
}
catch (Exception ex)
{
return ex.Message;
}
}
I think you need not mention localhost just the path to the file will do. or replace it with IP of the localhost.
Sorry i have dont a mistake the name i appended in javascript is not save as the name i gave in web api.
I changed,
file.append('tax_file', $('input[type=file]')[0].files[0]);
To
file.append('file', $('input[type=file]')[0].files[0]);
and it worked .
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'm having a problem sending a file object to python through an ajax call.
I'm using Dropzone just as my "file uploader interface" and I'm sending a call when certain button is pressed.
In python when I try to process the file, it says " 'str' object has no attribute 'seek' "
My JS Code:
...
window.$form_add_file = $("#form_add_file");
var file = dropzone.files[0];
...
var formData = $form_add_file.serializeArray();
if(file){
$modal_add_file.find($drop_add_file).removeClass("error");
var filetype = file.type.split("/")[0].toLowerCase();
var hasFile = checkFileType(filetype);
if(!hasFile) { filetype = "file" }
formData.push(
{ name: "file", value: file },
{ name: "file_type", value: filetype },
{ name: "file_name", value: file.name },
{ name: "file_size", value: file.size }
);
} else {
error = true;
$modal_add_file.find($drop_add_file).addClass("error");
return false;
}
if(!error){
$.ajax({
method: "POST",
url: host + "json.references.new",
data: formData,
cache: false,
dataType: 'json',
success: function(data){
if(data){
if(data.error){
modalMessage($modal_add_file, data.error, "ok");
} else {
refreshData(data);
}
}
},
error: function(error){
modalMessage($modal_add_file, oops_message, "ok");
}
});
}
My Python Code:
try:
file_path = os.path.join(path, file_name)
temp_file_path = file_path + '~'
file.seek(0) # error happen here
with open(temp_file_path, 'wb') as output_file:
shutil.copyfileobj(file, output_file)
os.rename(temp_file_path, file_path)
I've been searching for this on the internet and found nothing yet.
Sorry for the poor english.
Thanks in advance!
seek is a method for file objects, not strings.
I think your code snippet is missing some lines, but if file is supposed to be the file pointed to by file_path then you should first open the file with file = open(file_path, 'rb'). New file objects should start reading at the 0th position, so file.seek(0) should be unnecessary.