from curl to HTTPS request - javascript

I have a problem to transform this cURL:
curl -F email=myname#example.com -F file=#file.txt https://srv-file6.gofile.io/uploadFile (srv-file6.gofile.io is an example in reality is something like srv-store6.gofile.io , saw from request itself)
into an HTTPS request on node.js.
var xmlhttprequest = require ("xmlhttprequest").XMLHttpRequest;
var xhr = new xmlhttprequest();
xhr.open('POST','https://srv-store6.gofile.io/uploadFile',false,null,null);
xhr.setRequestHeader('Content-Type','multipart/form-data');
xhr.send('email=test#test.com&file=C:\\Users\\marco\\Pictures\\programming\\Cattura.png');
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseText);
}
}
I've tried using xmlhttprequest but doesn't work, I don't get any error message as responce but it dont upload the file.
Thats the site i took the api cURL from : https://gofile.io/api

In order to send the file, first you need to read it in side your code. You can read the file and then send. Otherwise, you can use the below example which uses fs library to read the file and then node-fetch library to send the file.
First, install the node-fetch library:
npm i node-fetch
Then, try the below example:
const fetch = require('node-fetch');
var FormData = require('form-data');
let fs = require('fs');
let file = fs.createReadStream('C:/Users/marco/Pictures/programming/Cattura.png');
var formData = new FormData();
formData.append('file', file );
formData.append('email', 'test#test.com' );
// #ts-ignore
fetch('https://srv-store6.gofile.io/uploadFile', {
method: 'POST',
body: formData
})
.then(function(res) {
return res.json();
}).then(function(json) {
console.log(json);
});

I suggest you to follow the instruction reported here https://developer.ibm.com/recipes/tutorials/uploading-files-to-web-server-using-ajax-xhr/
Is it a server side operation or is it used by a front end page? Please post your front page also.
You are sending a string not a file data.
var formData = new FormData();
formData.append(‘myFile’, files[0], files[0].name);
var xhr = new XMLHttpRequest();
xhr.open(‘POST’, ‘/upload’, true);
xhr.onload = function () {
if (xhr.status === 200) {
alert(‘File successfully uploaded’)
} else {
alert(‘File upload failed!’);
}
};
xhr.send(formData);

Related

Upload images to a Node.JS server without using <form>

I have a node.js server, which uses express-fileupload to accept images. Now I'm working on the function to upload an image. But I don't want to use < form > since I prefer xhtml request for various reasons, but mainly because I don't want to redirect the user, after he uploads an image.
I have tried reading the picture as dataURI, sending it to the server, decoding it and writing it to a file, which didnt work and seemed to resource intensive and laborious.
//I used the dataString from the callback method and wrote it to a file using fs.writeFile
function dataURItoimage(dataString, callback){
const atob = require("atob");
dataString.replace("data:image/jpeg;base64,", "");
dataString.replace("data:image/png;base64,", "");
atob(dataString);
callback(null, dataString);
}
//User side code
avatarInput.addEventListener("change", (e) => {
const reader = new FileReader();
reader.readAsDataURL(avatarInput.files[0]);
reader.onload = () => {
avatar = reader.result;
tosend.avatar = reader.result;
}
}, false);
uploadButton.onclick = () => {
var request = new XMLHttpRequest();
request.open("POST", "/avatarUpload");
request.setRequestHeader("Content-Type", "application/json");
var tosend = {avatar: ""};
tosend.avatar = avatar;
request.send(JSON.stringify(tosend));
}
Is there a better way to upload an image, which the user can select, to a node.js server?
You can try this example. It worked for me. I hope it can help you.
Sending dataURL throw Ajax request:
const dataURL = snapshotCanvas.toDataURL('image/png');
$.ajax({
url: 'http://localhost:3000/upload-image',
dataType: 'json',
data: { data: dataURL },
type: 'POST',
success: function(data) {}
});
Receiving request:
router.post('/', (req, res) => {
const base64 = req.body.data.replace(/^data:image\/png;base64,/, "");
fs.writeFileSync(`uploads/images/newImage.jpg`, base64, {encoding: 'base64'});
}
So I did it this way:
var request = new XMLHttpRequest();
request.open("POST", "/test");
var fd = new FormData();
fd.append("file", avatarInput.files[0]);
request.send(fd);
I created a FormData Object, appended the image, which the user chose in an input called "avatarInput", and send the object to the server.
On server side I used express-fileupload to access the file:
app.post("/test", (req, res) => {
if(req.files){
//With the follwing command you can save the recieved image
req.files.file.mv("./file.png", (err) => {if(err)throw err});
}
res.end();
});

setting up tinymce with cloudinary in html and javascript

I've read the readme file at https://github.com/cloudinary/cloudinary_tinymce but still can't understand how to do it. Plus they do it on Ruby on Rails, which doesn't really help.
Do I really need to do server-side endpoint? It only asks for a signed URL. But I don't need it to be signed. How do I do it within JavaScript and HTML alone? I don't want to do anything inside my server except to render templates.
edit: I tried it with image_upload handler and it uploads to my Cloudinary account. But it won't give me the url for the image on successful upload (I expect to get something like https://res.cloudinary.com/strova/image/upload/v1527068409/asl_gjpmhn.jpg). Here's my code:
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
xhr.open('POST', 'https://api.cloudinary.com/v1_1/strova/upload');
xhr.onload = function () {
var json;
if (xhr.status !== 200) {
failure('HTTP Error: ' + xhr.status);
return;
}
json = JSON.parse(xhr.responseText);
success(json.location);
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
formData.append('upload_preset', cloudinary_upload_preset);
xhr.send(formData);
}
Try "faking" a POST request for one. I am still trying. To figure out why the documentation "requires" a POST request. The PHP example: https://www.tinymce.com/docs-3x//TinyMCE3x#Installation/ just echos back what gets POSTED to server. The plugin must be interpolated the posted content.
Inspired by your code, I was able to resolve this pain point for myself. The missing part was that after parsing the response, the secure_url from the response needed to be called and assigned to json in the format required by TinyMCE. Following is the code:
images_upload_handler: function (blobInfo, success, failure) {
var xhr, formData;
xhr = new XMLHttpRequest();
xhr.withCredentials = false;
//restricted it to image only using resource_type = image in url, you can set it to auto for all types
xhr.open('POST', 'https://api.cloudinary.com/v1_1/<yourcloudname>/image/upload');
xhr.onload = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
var url = response.secure_url; //get the url
var json = {location: url}; //set it in the format tinyMCE wants it
success(json.location);
}
};
formData = new FormData();
formData.append('file', blobInfo.blob(), blobInfo.filename());
formData.append('upload_preset', '<YourUnsignedUploadPreset>');
xhr.send(formData);
}

XMLHttpRequest file upload returning a 500 error

I am trying to upload a file using XMLHttpRequest() but the post request is returning a 500 internal server error. I've made sure the file parameter is sending through the file object and that the action URL is correct. Am I missing something?
HTML:
<input type="file" class="form-control" name="documents" (change)="onFileUploadChange($event)">
Component:
onFileUploadChange(_event: any) {
let file = _event.srcElement.files;
let postData: any = null;
this._fileUploadService.uploadFile(this.uploadURL, file);
}
Service:
uploadFile(_url:string,_file:File):Promise<any> {
return new Promise((resolve, reject) => {
var xhr:XMLHttpRequest = new XMLHttpRequest();
console.log(_file);
console.log(_file[0].name);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
// ...
} else if (xhr.status === 500) {
// ...
}
else {
// ...
}
}
};
var formData = new FormData();
formData.append('file', _file[0], _file[0].name);
xhr.open('POST', _url, true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type','multipart/form-data');
xhr.send(formData);
});
}
A 500 error means the request got to the destination and there was a problem at the destination. Try checking the destination for errors.
Maybe you send wrong request? Last time I've got the same problem and there was a solution:
Saving Blob as xlsx in Angular2

XMLHttpRequest text send 404 error

I have a text file on my server and I want to upload a text in it using XMLHttpRequest. It is downloaded successfully via GET method, but when I try to POST it I get 404 error.
var r1 = new XMLHttpRequest();
r1.open("GET", "db.txt", false);
r1.send();
var str = r1.responseText + "foo text";
var r2 = new XMLHttpRequest();
r2.open("POST", "db.txt", false);
r2.send(str);
Doing a direct upload as you're trying would be a security concern in most places and is generally not permitted... What you need to do is have a middle layer on your server to handle the request and write the file to disk safely.
You can easily upload a file using something like this:
var jsonBlob = new Blob([someJSON], {type: "text/plain;charset=utf-8"});
var data = new FormData();
data.append("filename", "new.json");
data.append("json", jsonBlob);
var xhr = new XMLHttpRequest();
var postURL = "http://example.com/post_target";
xhr.open("POST", postURL, true);
xhr.onload = function(e) {
if (this.status == 200) {
console.log(e.target.response);
}
};
xhr.send(data);
Where postURL is an endpoint which can handle file uploads.
If you post what language(s) you have available on your server (PHP?) I can give some example code to handle the upload on the server's end.

Handling POST Request

I'm creating a asynchronous upload element with the javascript code bellow:
$("#file-input").change(function(){
uploadImage(this.files[0]);
});
function uploadImage(imageFileHTMLInput) {
var xml = new XMLHttpRequest();
var data = new FormData();
data.append('file', cover);
xml.open('POST', url);
xml.send(data);
xml.onreadystatechange = function() {
if(xml.readyState === 4) {
if(xml.status === 200) {
var response = JSON.parse(xml.responseText);
// handle response
} else {
var error = JSON.parse(xml.responseText);
// handle error
}
}
};
}
How can I handle this post in a Symfony2 server? I need to save this file in the server and return the image url.
UPDATED:
I made some changes on my code to works fine. I have change all way to do the upload.
You will get the data from your POST request in the controller via
$request->files->get('your_file_identifier_name');
Server side, you'll get an instance of File

Categories