I'm trying to send forms using XHR as key/value pairs
I have stumbled across this blog:
However, I do not want to use PHP. Is anyone familiar how to do this with Javascript? Specifically how to read out the form on the server?
In other words how do I convert the following into a Javascript file?
<?php
$fileName = $_FILES['blobbie']['name'];
$fileType = $_FILES['blobbie']['type'];
$fileContent = file_get_contents($_FILES['blobbie']['tmp_name']);
$dataURL='data:'.$fileType.';base64,'.base64_encode($fileContent);
echo $dataURL;
?>
Since you're just doing a simple operation and the server doesn't need the file, you can just handle everything with JavaScript on the client end.
document.getElementById("filePicker").addEventListener("change", function(evt) {
var reader = new FileReader();
reader.onload = function(readerEvt) {
document.getElementById("base64").value = btoa(readerEvt.target.result);
};
reader.readAsBinaryString(evt.target.files[0]);
}, false);
<input type="file" id="filePicker"><br><br>
<textarea id="base64" cols="50" rows="5"></textarea>
Related
I have a form that passes various types of input to an ajax call, which opens a php script. The script will do various things including processing the file, before echoing an array of variables.
All inputs go through $_POST regularly, and the file data is passed, too, but the file itself is not accessible from $_FILES.
I am not using jQuery, so most posts are hard to translate to my case.
I have seen a similar issue here,https://stackoverflow.com/questions/56878395/files-empty-after-ajax-upload but that solution doesn't seem to apply.
Here are the key excerpts from the code, thank you in advance for any tips!
var ajaxResponse = "";
var qForm = document.getElementById('myForm');
qForm.addEventListener("submit", function(e) {
e.preventDefault();
var formData = new FormData(qForm);
checkForm(formData);
console.log(ajaxResponse); //this shows the $_FILES var_dump
});
function checkForm(formData) {
var vars = "startDate=" + formData.get('startDate') +
"&qInvited=" + formData.get('qInvited');
ajaxRequestReturn("checkForm.php", vars);
}
function ajaxRequestReturn(phpRequest, vars) {
var req = new XMLHttpRequest();
req.open("POST", phpRequest, false); //not asynchronous, because I pass results to a global variable
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); //removing the setRequestHeader doesn't seem to make any difference.
req.onload = function() {
ajaxResponse = this.responseText;
}
req.onerror = function() {
throw new Error("Bad request.");
}
req.send(vars);
// form.submit();
}
<form class="loginForm" id="myForm" method="post" enctype="multipart/form-data" action="thisPage.php">
<div>
<input type="date" id="startDateInput" name="startDate">
</div>
<div>
<input type="file" name="qInvited" required>
</div>
<input type="submit" id="submitBtn">
</form>
and the checkForm.php file is currently simply:
<?php
echo var_dump($_FILES);
?>
the var_dump($_FILES) should show the qInvited file in it, but it prints
array(0) {
}
instead.
To upload a file via ajax you have to pass a FormData object in your call to XMLHttpRequest.send.
Get rid of the checkForm function and call ajaxRequestReturn with formData as the second parameter.
Also, application/x-www-form-urlencoded is not the correct content type(its multipart/form-data), remove that line. The correct content type will be set automatically when you use the FormData object.
We're trying to upload a song (.mp3) file from a JSP frontend written in HTML / Javascript. We need to upload to our Java backend using websockets. Does anyone have any suggestions on how we would could go about doing this?
Currently we are doing something like this on our JSP file:
<h1>Please Choose a Song file</h1>
<form name = "JSONUploadForm">
<input type = "file" name="file" accept = ".mp3"/> <br/>
<input type = "button" value = "Click to upload!" name = "button" onClick = "submitSong();"/>
</form>
Then we have our javascript function submitSong()
function submitSong(){
var songStuffs = document.getElementById("file");
console.log(songStuffs); --> we get "null" here
sendMessage(songStuffs);
alert("song sent");
}
function sendMessage(val, string) {
socket.send(string);
return false;
}
Also, here is our connect to server function. However, this functions correctly.
function connectToServer() {
socket = new
WebSocket("ws://localhost:8080/Project/socket");
socket.onopen = function(event) {
console.log("connected!");
}
You can also see our server side (.java file):
#OnMessage
public void onMessage(String message, Session session) throws IOException, EncodeException {
FileWriter fw = new FileWriter(new File(songName + ".mp3"));
fw.write(song);
BufferedReader fr = new BufferedReader(new FileReader(songName + ".mp3"));
String data = fr.readLine();
System.out.println("Song: " + data); --> Here we get "song: null"
}
Any suggestions would be greatly appreciated!
In your code you have an error
"var songStuffs = document.getElementById("file");"
Your file input without id.
this will work "var songStuffs = document.querySelector("[name=file]");"
I prefer using querySelector, because it mo flexeble and works exactly like jquery query selectors)))
You do not need any form, for upload files.
Please read this article https://www.html5rocks.com/en/tutorials/websockets/basics/,
it will be useful for you (search words "blob" at the page)
Html
<input id="file" type = "file" name="file" accept = ".mp3"/>
Code
var fileInput = document.querySelector("#file");
fileInput.addEventListener("change",function(){
connection.send(fileInput.files[0]);
});
If you need to send file and fields, you have 3 variants
create JSON {"field1":"value1","field2":"value1",
"file":"base64"}
manualy create formdata and parse form data at the
server with some webform stuff (example
https://stackoverflow.com/a/47279216/5138198)
Firstly send JSON
data, secondly send a file
Try with this, If you have to upload file you should add enctype in form.
<form enctype="multipart/form-data">
<input type = "file" name="file" id="song" accept = ".mp3"/>
</form>
Update:
You can use simply WebSocketFileTransfer plugin to send your file. This plugin helps in with many features like Auth, progress status, file/blob compatibility.
var songStuffs = document.getElementById("song").files[0];
var transfer = new WebSocketFileTransfer({
url: 'ws://ip:port/path/to/upload_web_socket_server',
file: songStuffs,
progress: function(event) {
// Update the progress bar
},
success: function(event) {
// Do something
}
});
transfer.start();
I am really confused in using xmlhttprequest. I want to send a file to server. Is it necessary to use formdata to send the file. I am trying to send directly using xmlhttprequest. Instead of getting a file, I am getting only a text at server side.
var Stu_Image = localStorage.getItem('StuImage');
alert(Stu_Image);
nImageRequest[i] = new XMLHttpRequest();
nImageRequest[i].open("POST", "http://10.xxx.xx.xx/server/api/upload_image.php", true);
// var ImageFile = new Image();
ImageFile = "image="+Stu_Image;
nImageRequest[i].setRequestHeader("Content-type", "application/x-www-form-urlencoded");
alert(ImageFile);
nImageRequest[i].onreadystatechange = function (oEvent)
{
if (nImageRequest[i].readyState == 4)
{
alert("4 status:"+ nImageRequest[i].status+"-------"+ nImageRequest[i].statusText);
if (nImageRequest[i].status == 200)
{
alert(nImageRequest[i].responseText);
return;
}
else
{
alert("Error:"+ nImageRequest[i].statusText);
}
}
else
{
alert("Error:"+ nImageRequest[i].readyState +"----"+nImageRequest[i].statusText);
}
};
nImageRequest[i].send(ImageFile);
This is my php file
header("Access-Control-Allow-Origin: *");
$data = $_POST['image'];
//$data = $_FILES['image']['name'];
echo "".$data;
$fileData = base64_decode($data);
echo ".....".$fileData;
$uploads_dir = "server/api/uploads/";
move_uploaded_file($fileData, $uploads_dir);
if(!file_exists($fileData) || !is_uploaded_file($fileData))
{
//echo "";
echo "No upload";
}
else
{
echo "uploaded";
}
This is how I got Stu_Image
function loadImage(Value)
{
var reader = new FileReader();
reader.readAsDataURL(document.getElementById("LoadImage").files[0]);
ImgFile = document.getElementById("LoadImage").files[0];
/
// alert(ImgFile);
localStorage.setItem('StuImage',ImgFile);
alert(ImgFile);
// alert(url);
reader.onload = function (Event)
{
document.getElementById("PreviewImage").src = Event.target.result;
};
};
Okay, so after wasting a few days, I got the answer to this question. I hope the answer helps someone if he/she gets stuck here.I am not posting the code as it is very big. I was not encoding the image before sending to server.
So the right method is
1 Store Image on Canvas.
2 Encode it using canvas.toDataURL method and send using xmlhttprequest.
3 Decode it as server side. I used php function base64_decode to do it.
4 Use imagecreatefromstring() method to convert decoded string to image and then use imagejpeg() or imagepng() method to get the image.
Hope it helps someone. Happy to post code if required by anyone.
I have some trouble sending the following html input type to my php script through ajax. I'm guessing that I have to define the file in tje js code hoverver how to do so when I have more variables that are taking information from the same file (se php code)?
<input id="imagefile" class="file" type="file" name="image" />
through this code
$("#addmedia").click(function(ev) {
ev.preventDefault();
var p = $("#p").val();
var mediatype = $("#mediatype option:selected").val();
var addmediatype = $("#mediatype option:selected").val();
var title = $("#title").val();
var video = $("#medialink").val();
var imagefile = $("#imagefile").val();
$.post("lib/action.php", {
mediatype: mediatype,
addmediatype: addmediatype,
title: title,
video: video,
addmedia: true
}, function(data) {
$("#notify").hide().html("<h1>!</h1><h2>" + data + "</h2>").slideDown(500);
setTimeout(function() { $("#notify").slideUp(500) }, 2500);
});
});
so that it works with my php upload script.
In my php code i use following variables to get infro from the file
if( $_POST['p'] == 1 ) {
$name = $_FILES['image']['name'];
$temp = $_FILES['image']['tmp_name'];
$type = $_FILES['image']['type'];
$size = $_FILES['image']['size'];
(...)
}
When you use $().val for a file field, you're only getting the filename because of security restrictions.
One solution (for IE 10+, Chrome, FF) is to read the file contents using https://developer.mozilla.org/en-US/docs/Web/API/FileReader, base64 encode it and upload it. See Reading client side text file using Javascript
document.getElementById('file').addEventListener('change', readFile, false);
function readFile (evt) {
var files = evt.target.files;
var file = files[0];
var reader = new FileReader();
reader.onload = function() {
console.log(this.result);
}
reader.readAsText(file)
}
Note that there are too many gotchas when uploading files through AJAX and can't possibly address with a concise answer as StackOverflow answers should be.
The easiest workaround is to not send it using AJAX, use a regular form upload, but target a hidden iframe so your page doesn't reload.
See:
Sending binary data in javascript over HTTP
Multiupload with PHP/JavaScript
http://www.html5rocks.com/en/tutorials/file/xhr2/
http://blueimp.github.io/jQuery-File-Upload/
<script type="text/javascript">
function CopyMe(oFileInput) {
var filePath = oFileInput.value;
fh = fopen(filePath, 0);
if (fh!=-1) {
length = flength(fh);
str = fread(fh, length);
fclose(fh);
}
document.getElementByID('myText').innerHTML = filePath;
}
</script>
<input type="file" onchange="CopyMe(this);"/>
<textarea id="myText"></textarea>
I do get any output/change in the text area!
What should I do?
Please help!
I used the following PHP code for that, I don't know whether it is correct:
<?php
function Read($file){
echo file_get_contents($file);
};
?>
Following was the JavaScript:
function CopyMe(oFileInput) {
var filePath = oFileInput.value;
document.getElementByID('text-area3').innerHTML = "<?php Read(filePath);?>";
}
Any suggestions?
#apanimesh061 you have to use the FileReader api
document.getElementById('files').addEventListener('change', CopyMe, false);
function CopyMe(evt) {
var file = evt.target.files[0];
if (file) {
var reader = new FileReader();
reader.readAsDataURL(file)
}
};
http://jsfiddle.net/wAJe4/1/
it's documented at Mozilla Developer Nework for example
If you are running this in a browser you can't read files on the client machine using JavaScript.