Store image on server with html/javascript/mongodb - javascript

I want to upload an image from a user to the server. With the all path, it works (I can store on MongoDB). But with <input id ='image_upload' type='file' name='image_upload' />, it doesn't works (security, no full path)
So I want to know if there is an other way to do that. Maybe asolution where I store directly on the server will be ok (Using javascript, html, ajax, ... )
Thank you

You can use form data as such:
https://developer.mozilla.org/en-US/docs/Web/API/FormData/Using_FormData_Objects
Paticularly,
var formData = new FormData();
// HTML file input, chosen by user
formData.append("userfile", fileInputElement.files[0]);

Related

How to save html form data in txt file using javascript

I have a html form. I want to store form data in another txt file using javascript.
For ex: I have a html form and store-data.txt file . when user fill the form and hit submit, so data stored in store-data.txt file.
How I will do this using javascript.
Javascript can`t save data on server. JS can save data on clients machine. Data on clients machine can be stored using cookie. But I feel, it isnt an aim. Store data from froms can server side apps, driven like php.
You can use filesaver.js library for a clean implementation or follow along with this codepen It is the quickest.
if you wanted to store input values assign all values in an object then JSON.stringify then throw it to this function to get text file of json
function createTextFile(str){
var file = new Blob([str])
anchor = document.createElement("a")
anchor.href = URL.createObjectURL(file)
anchor.download = "fileName"
anchor.click()
URL.revokeObjectURL(anchor.href)
anchor.remove()
}
var input = "this is a string to test"
createTextFile(input)
and if you wanted to save in server side with php there is function in php
file-put-contents

Sending data from javascript to php to generate a pdf but doesn't work

I am using JavaScript to take the info from a form completed by the user, then sending this data to PHP and generate a PDF with FPDF. The problem is I want the browser to ask the user to save the PDF or view it online but
I cannot figure out how. The PDF generates correctly but only when I save it directly to a certain path specified by me.
The question is how do you guys send data from JavaScript to PHP to generate a PDF file then the browser asks the user to open or download, Or how can I make a function where the user can retrieve this PDF.
The JavaScript:
function senddata() {//this activates when i push a button not a submit
var peticion = new XMLHttpRequest();
peticion.open('POST', 'generatepdf.php');
var nueva2 = {};
var key;
for (i = 0; i < 6; i++) {
key = document.forms[0].elements[i].id;
nueva2[key] = document.forms[0].elements[i].value;
}//here i take my data from the form and make an object
var json = JSON.stringify(nueva2);//here i tranform my object to json string so i can send it to my php
var parametros = "json_string=" + json;//here I do this so later I can easily transform the $_POST to an array in the form json_decode($_POST["json_string"],true);
peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
peticion.send(parametros);//it sends ok
}
The PHP with the FPDF class and things
<?php
require('fpdf/fpdf.php');
require('functions.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
$datos=json_decode($_POST["json_string"],true); //here i have my data in an array format so i can use the parameters to fill my pdf fields
//...lots of pdf things here...//
$pdf->Output('F',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this works but never ask the user
//$pdf->Output('D',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this should force a dowload or send to the browser but doesnt work
//$pdf->Output();//this should send to the browser but doesnt work
}
To view your PDF inline to the browser, you should use the I variable instead. View full documentation here.
Also I don't think outputting the file in two methods at the same time works. It might conflict each other. The best way to do that is to test each method and if it does conflict each other just simply add a condition for the user to decide whether he/she wants to download or view it in the browser. Hope this helps.

Does fetch support multiple file upload natively?

Summary
I am trying to set my FormData properly using javascript.
I need to be able to upload jpg/png, but I might need to upload some other file types pdf/csv in the future using fetch.
Expected
I expect it to append the data to the form
Error
Working
This snippet is working fine:
const formData = new FormData(document.querySelector('form'));
formData.append("extraField", "This is some extra data, testing");
return fetch('http://localhost:8080/api/upload/multi', {
method: 'POST',
body: formData,
});
Not working
const formData = new FormData();
const input = document.querySelector('input[type="file"]');
formData.append('files', input.files);
Question
Does fetch support multiple file upload natively?
If you want multiples file, you can use this
var input = document.querySelector('input[type="file"]')
var data = new FormData()
for (const file of input.files) {
data.append('files',file,file.name)
}
fetch('http://localhost:8080/api/upload/multi', {
method: 'POST',
body: data
})
The issue with your code is in the lineformData.append('files', input.files);
Instead of that, you should upload each file running a loop with unique keys, like this
const fileList = document.querySelector('input[type="file"]').files;
for(var i=0;i<fileList.length;i++) {
formData.append('file'+i, fileList.item(i));
}
I have created a simple error fiddle here with your code. You can check its' submitted post data here, where you can see that no file has been uploaded.
At the bottom of the page you can find
.
I have corrected the fiddle here with the fix. You can check its'post data from the server, where it shows the details of the two files that I uploaded.
I mentioned this on a similar question: I had the same problem, but with a PHP backend. The unique formData keys work, but I found that the classic HTML notation worked just fine and simply results in an array on the server.
formData.append('file[]', data[i]);
I like that a lot better, since I can use the same methods to process this as with a classic <input type="file" multiple />.

mod_wsgi: Reading POSTed file content remains empty

I don't get it, I don't understand.
In a self-developed Python web framework I'm posting a file form element to the server using JavaScript.
var formData = new FormData();
formData.append('file', document.getElementById('file').files[0]);
var request = new XMLHttpRequest();
request.open("POST", url, true);
request.send(formData);
The server, sporting mod_wsgi, receives the request like so:
if environ['REQUEST_METHOD'] == 'POST':
post_env = environ.copy()
post_env['QUERY_STRING'] = ''
form = cgi.FieldStorage(
fp=environ['wsgi.input'],
environ=post_env,
keep_blank_values=True)
Then, when I want to access the form field's content to save it to a file, the following will return an empty result:
form['file'].file.read()
(All code has been edited for simplicity)
What puzzles me is that the form field will show the correct file name and MIME type, only file.read() remains empty.
Also all other information from other input text fields comes through and is accessible.
I also checked that environ['REQUEST_METHOD'] is actually POST.
As to HTTP Headers for encoding (such as multipart/form-data), I thought that the XMLHttpRequest object will take care of that, once formData.append() receives a file input as the value.
Okay, here's the solution:
I can't explain it, but the file form fields get emptied on first read, which I found out by accident. Maybe a bug, who knows.
I assumed that they would stay intact (like any other variable) and can be read multiple times.
What I ignored was that I had in fact addressed them several times.
So the solution was to first store the file's content in a variable, and then use that multiple times.

Ajax using file upload

I am creating mail page for sending mails. I need to attach some file before sending. How could I do this using AJAX? Initially I need to store those files in server and then I have to send the mail. These actions are done with in a single send button.
Check these questions:
JavaScript file uploads
How can I get Gmail-like file uploads for my web app?
What is the best multiple file JavaScript / Flash file uploader?
Look on below snippet which send text data and attached multi-files. The content-type='multipart/form-data' is set by browser automatically, the file name is added automatically too to filename FormData parameter (and can be easy read by server).
async function sendEmail() {
let formData = new FormData();
let msg = { message: emailText.value };
formData.append("email", JSON.stringify(msg));
[...attachment.files].map( (file,i) => formData.append("file"+i, file) );
try {
await fetch('your/api/upload/email', { method: "POST", body: formData });
alert("Email was send!");
} catch(e) {
alert("Problem with email sending");
}
}
<textarea id="emailText" placeholder="Type message here"></textarea><br>
<input type="file" id="attachment" multiple /><br><br>
<input type="button" value="Send email" onclick="sendEmail()" />
<br><br><span style="color:red">In this snippet API not exists so exception will be thrown but you can look on your request in:<br> chrome console> network tab</span>
I hope you know how do the normal upload. Call the upload/Reading and updating the file when click the button by using the ajax call. You have to send the local system file path as the input and then the response should contain the path in the server or error. Update the attachment link with the response in case there are no errors.
You should dynamically create a hidden iframe in your DOM and set the target of your upload form to this iframe. dont forget to set form method to POST.
you could do both uploading and message field filling in one go.
you should definitely check ready components doing this for the javascript library of your choice.

Categories

Resources