How to make formData object from image URL - javascript

I want to make image upload from url for example: http://.. ../logo.png
I need to make formData object from image url but it doesn't work:
HTML:
<form id="form-url">
<input type="text" class="image" id="textarea" placeholder="URL" />
<button>UPLOAD</button>
</form>
Javascript:
$("#form-url").submit(function(e) {
if ($(".image").val() != "URL" && $(".image").val() != "") {
//I also tried this:
var data;
var img = new Image();
img.src = $(".image").val();
img.load = function(){
data = getBase64Image($(".image").val());
};
//but it send undefined
//and this:
var data = URL.createObjectURL($(".image").val()); //dont work
//error: TypeError: Argument 1 is not valid for any of the 1-argument overloads of URL.createObjectURL.
//Upload process working on normal input type file uploading but no on URL image
var formData = new FormData(data);
formData.append("fileToUpload", data);
var xhr = new XMLHttpRequest();
xhr.open('POST', "upload_ajax.php", true);
xhr.onload = function () {
if (xhr.status === 200) {
data = xhr.responseText;
datas = data.split("_");
if (datas[0] != "true") {
alert(data);
} else {
alert('YES');
}
} else {
alerter('An error occurred while uploading this file! Try it again.');
}
};
xhr.send(formData);
} else { alerter("Your file must be an image!"); }
return false;
});
My php script for debug:
<?php
if (isset($_POST)) {
var_dump($_POST);
if (empty($_FILES['fileToUpload']['tmp_name'])) {
echo "Your file must be an image!";
} else {
echo $_FILES['fileToUpload']['name'];
echo $_FILES['fileToUpload']['size'];
}
}
?>
Thanks for all help and your time..
and sorry for my bad english (student)

If getBase64Image is from here, or is similar to it.
Then you are using it wrong. You need to pass it the image node itself. Also the image onload event is async, and as such you have to wait for it to be done to get the data and send it.
var xhr = new XMLHttpRequest();
var formData = new FormData();
xhr.open('POST', "upload_ajax.php", true);
...
var img = new Image();
img.onload = function(){
var data = getBase64Image(this);
formData.append("fileToUpload", data);
xhr.send(formData);
};
Also note on the server side you will need to decode it from the base64 encoding, as it is being sent by string, it is going to be in $_POST not $_FILE
var rawContents = base64_decode($_POST['fileToUpload']);
Note you could also just send the url to the php script and just have php get the image data
var rawContents = file_get_contents($_POST['imageurl']);

Related

How do I upload a file using FormData and XmlHTTPRequest?

I'm trying to send a file from a web page to a php script using FormData, and the file isn't showing up in the $_FILES variable in the PHP page. Not sure if my error is on the JS side or the PHP side, or if I'm misunderstanding something deeper about the process.
Here's my code:
function uploadFile() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log('success');
} else {
console.log('error');
}
}
};
xhr.open('POST','php/parsefile.php',true);
xhr.setRequestHeader("Content-Type","multipart/form-data");
var formData = new FormData();
formData.append("myfile", document.querySelector('#fileInput').files[0]);
xhr.send(formData);
}
<input type="file" id="fileInput">
<button onclick="uploadFile();">Upload</button>
Here's parsefile.php:
<?php
echo("Error: " . $_FILES["myfile"]['error'] . "\n");
echo("Name: " . $_FILES['file']['name'] . "\n");
When I upload a simple, small (64 bytes) text file, the console reads success, but the response from the server is just this:
Error:
Name:
What am I missing here? Thanks for any help anyone can provide.
I found two issues in your code:
In JavaScript code, you explicitly defined the "Content-Type" as "multipart/form-data". JS automatically gets the content type when you make the XHR Request.
In the 4th line of your PHP code, the key of the $_FILE is "file". You need to change it to "myfile", in order to make it work.
You can check my edited code below:
JS Code:
function uploadFile() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log('success');
} else {
console.log('error');
}
}
};
xhr.open('POST','php/parsefile.php',true);
var formData = new FormData();
formData.append("myfile", document.querySelector('#fileInput').files[0]);
xhr.send(formData);
}
PHP Code:
<?php
echo "Name: ". $_FILES['myfile']['name'];
echo "Error: ".$_FILES['myfile']['error'];

Upload file with pure Javascript and PHP

I get stuck with my script and I hope somebody can help me.
I try to send a file to the server with Javascript and PHP.
For this I created a file input element
<input type="file" class="quote_attachment" id="quote_attachment"/>
With Javascript I create a request
<script type="text/javascript">
document.getElementById("quoteform").addEventListener("submit", function(){
var attachment = document.getElementById("quote_attachment").value;
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://www.mysite/mailer/mailer.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('&attachment='+attachment);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
}
}
event.preventDefault();
});
</script>
On the serverside I do this with PHP
<?php
if(isset($_POST['attachment'])){
$allowed = array('ai', 'AI', 'eps', 'EPS', 'pdf', 'PDF', 'svg', 'SVG');
if($_POST['attachment'] !== ''){
$get_extension = pathinfo($_POST['attachment'], PATHINFO_EXTENSION);
if(!in_array($get_extension, $allowed)){
$errors[] = 'Dit type ondersteunen wij niet';
}else{
if(!move_uploaded_file($_FILES["attachment"]["tmp_name"], 'quoteattachment/')){
echo 'there is something wrong with uploading the file.';
}
}
}
}
?>
This is not the whole code but only the part of the file handling.
If I run the code I get the error "there is something wrong with uploading the file.
Who can help me further with this?
Using document.getElementById("quote_attachment").value; will just return the name of the file in the file input.
You should use .files and pass it into a formData object. For example:
<script type="text/javascript">
document.getElementById("quoteform").addEventListener("submit", function(){
// Get the files in input
var files = document.getElemenyById("quote_attachment").files;
// Create formData object
var formData = new FormData();
// Might or not be a multi file input, so loop through it
for (var i = 0; i < files.length; i++) {
var file = files[i]
formData.append('files[]', file);
}
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "https://www.mysite/mailer/mailer.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send('&attachment='+formData);
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
}
}
event.preventDefault();
});
</script>
Now if you var_dump in your PHP-function you should get an Array containing all file data. If it does your PHP-function should run without problem.

Image src not updating after setRequestHeader call

I have two AJAX functions: one for an image file upload, one for a form info upload.
File Upload
function uploadFile(insertNodeID, inputFileID){
var img = document.getElementById(inputFileID).files[0];
var form_data = new FormData();
form_data.append('file[]', img, img.name);
var objXML = new XMLHttpRequest();
objXML.onprogress = updateProgress;
objXML.onload = function() {
if(objXML.readyState==4 && objXML.status==200) {
if(objXML.responseText !== 'no'){
document.getElementById(insertNodeID).src = objXML.responseText;
}
else{
errorInOut('There was a problem uploading the file.');
}
}
};
objXML.open('POST', baseURL+'ajax/admin_fileupload/', true);
objXML.send(form_data);
Form Info Upload
function uploadFormInfo(strURL, strData, type) {
strURL = baseURL+'ajax/'+strURL+'/';
var objXML = new XMLHttpRequest();
objXML.onreadystatechange = function() {
if (objXML.readyState == 4 && objXML.status == 200) {
returnXML(objXML.responseText, type);
}
};
objXML.open("POST", strURL, true);
objXML.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
objXML.send(strData);
They both work perfect independently.
The issue I'm running into is when I call the uploadFormInfo(), then call uploadFile(), the document.getElementById(insertNodeID).src does not render the uploaded image. It still uploads the image to the server and the responseText is the correct path to the image. I did a console.log on the .src of the id AFTER the I plugged in the new image and the .src is correct BUT, it never changes in the elements tab in Chome inspect. It also works fine BEFORE I call uploadFormInfo().
I've tried and number of things (sending a separate request header for the uploadFile) and nothing works.
I'm stumped.

Pass Base64 with POST Request

I am using javascript and I get a image file and encode it to base 64 like this
function el(id){return document.getElementById(id);} // Get elem by ID
function readImage() {
if ( this.files && this.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
el("img").src = e.target.result;
el("base").innerHTML = e.target.result;
};
FR.readAsDataURL( this.files[0] );
}
}
el("asd").addEventListener("change", readImage, false);
Where the encoded text is this and looks like this
data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/4gxYSUNDX1BST0ZJTE.........
And now I want to send this data with a post which I know how to do, but when I read the data I sent on the other side I just see data:image/jpeg, where does the Base64 encoded start and how can I just pass that as a string?
I make the post like this
var base64data;
//base64data is declared in the function readImage and I log it in this one and it has data
function callHttpReq () {
var http = new XMLHttpRequest();
var url = "/admin/website_sql/save_info.py";
var params = "website_photo=" + base64data;
http.open("POST", url, true);
console.log(base64data);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
console.log(http.responseText);
}
}
http.send(params);
Thanks

How to append multiple file inputs to a FormData object using $.each?

I have a multiple (and dynamic) number of inputs of type=file.
I want to create a FormData object out of them.
I need to manually append them to the object as I need access to their filenames for inserting into a database and therefore need to specify a filename is this format:
myFormData.append(name,file,filename);
HTML
<form id="my_form" enctype="multipart/form-data">
<input type="file" name="undefined" id="file_1" data-filename="image.jpg">
<input type="file" name="undefined" id="file_2" data-filename="image2.jpg">
<button>click</button>
</form>
jQuery
var myFormData = new FormData();
$(document).on("click", "button", function(e) {
e.preventDefault();
var inputs = $("#my_form input");
$.each(inputs,function(obj,v) {
var file = v.files[0];
var filename = $(v).attr("data-filename");
var name = $(v).attr("id");
myFormData.append(name, file, filename);
});
//alert(JSON.stringify(myFormData));
console.log(myFormData);
});
I don't think the object is being constructed properly and I haven't been able to correctly view the contents of the object to confirm this.
This is what I get in the console:
jsFiddle
http://jsfiddle.net/rwone/K7aMw/
There is no good way to see the contents of FormData. A trick would be to send it (POST) and look at the network status.
Example: http://jsfiddle.net/K7aMw/2/
$(document).on("click", "button", function (e) {
e.preventDefault();
var inputs = $("#my_form input");
$.each(inputs, function (obj, v) {
var file = v.files[0];
var filename = $(v).attr("data-filename");
var name = $(v).attr("id");
myFormData.append(name, file, filename);
});
var xhr = new XMLHttpRequest;
xhr.open('POST', '/echo/html/', true);
xhr.send(myFormData);
});
Then in the Network tab (F12) you'll see the added files when inspecting the headers.
//your files should be doing something here
var files = yourfileInput[type = file].files
//will upload
var formData = new FormData();
//other info request takes
formData.append("otherInfoKey", $("#otherInfoID").val())
//Now turn to files
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i])
}
//Request
var xhr = new XMLHttpRequest();
xhr.open("post", "/upload", true);
xhr.upload.onprogress = function(ev) {
var percent = 0;
if (ev.lengthComputable) {
percent = 100 * ev.loaded / ev.total;
//$("#yourprogress").width(percent + "%");
//or something like progress tip
}
}
xhr.onloadend = function(e) {
if (!/^2\d*$/.test(this.status)) {
alert(this.responseText)
}
}
xhr.onload = function(oEvent) {
if (xhr.status == 200) {
//go on
}
}
xhr.send(formData);

Categories

Resources