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/
Related
i want to give the file location url for the code to get my file instead of using input file in html part , to pass the file to the code
the code pasted below works if i use " input type= "file" " to get the file, but if i use url (like below) it gives a error
fileInput1.addEventListener is not a function
at window.onload
here is the code
window.onload = function() {
var z ="C:/Users/akash/Desktop/riidl/UTham.txt"
var fileInput1 = z;
if (fileInput1){
fileInput1.addEventListener('change', function(e) {
var file = fileInput1.files[0];
var textType = /text.*/;
if (file.type.match(textType)) {
var reader = new FileReader();
reader.onload = function(e) {
spamdata=reader.result;
document.getElementById('here').onclick = console.log(spamdata);
}
reader.readAsText(file);
}
});
}
}
Accessing local files is not allowed in JavaScript for security purposes.
Pl refer to this answer for more details.
https://stackoverflow.com/a/372333/3626796
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 have two usecases, first, users can pick a local file and upload it to the server. Second, users can pick a file that is already on the server (uploaded, emailed etc by them). I know there are lots of libraries that do this, but Is it possible to use the native file browser, and allow them to pick a file, stored on the server, using that? It's okay if all browsers are not supported.
Nope. The file browser is controlled by the browser and OS and you cannot make anything about which folder to show.
Do not believe it is possible for <input type="file"> dialog to reference filesystem other than users local filesystem.
It's okay if all browsers are not supported
A workaround would be to save names or references of uploaded files at an array or object, save actual uploaded file at FileSystem using requestFileSystem, provide user with list of uploaded files, when user selects file from list, retrieve File object from FileSystem using requestFileSystem.
See jQuery File Upload Plugin: Is possible to preserve the structure of uploaded folders?
Alternatively, as suggested by #Gorka, you can store uploaded file.names in an array or object locally where uploaded file object is stored at server same file name; populate <select> element with with <option>elements having file.name as value; at change event of select element use XMLHttpRequest or fetch to retrieve selected <option> value from server. For example,
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<input type="file" />
<select disabled>
<option>Choose File from server</option>
</select>
<br>
<label></label>
<br>
<iframe style="width:95vw;height:98vw"></iframe>
<script>
var input = document.querySelector("input[type=file]");
var select = document.querySelector("select");
var iframe = document.querySelector("iframe");
var label = document.querySelector("label");
var uploads = [];
select.onchange = function(e) {
var uploadedFile = uploads.filter(function(file) {
return file.name === e.target.value;
}).pop();
var url = "/uploads/" + uploadedFile.name;
fetch(url)
.then(function(response) {
return response.blob()
})
.then(function(file) {
// do stuff with `file`
var reader = new FileReader();
reader.onloadend = function(e) {
iframe.onload = function() {
label.textContent = url;
}
iframe.src = e.target.result;
}
reader.readAsDataURL(file);
})
}
input.onchange = function(e) {
var file = e.target.files[0];
// save reference to uploaded file name
uploads.push({
name: file.name,
});
// post file to server
var data = new FormData();
data.append("file", file, file.name);
var request = new XMLHttpRequest();
request.open("POST", "/path/to/server");
request.onload = function() {
var option = document.createElement("option");
option.value = file.name;
option.textContent = file.name;
select.appendChild(option);
if (select.disabled) {
select.removeAttribute("disabled");
}
alert(`${file.name} written to server`);
}
// save `file` as `file.name` at server,
// for example, at `/uploads/${file.name}`
request.send(data);
}
</script>
</body>
</html>
plnkr http://plnkr.co/edit/McvuErPOxyNJcpIZXl1G?p=preview
I have a function that sends data through data:JSON.stringify(formdata)using POST to a remove .NET webservice. I have no problem this far. What I want to do it to add also add a another value to the formdata JSON that will hold a base64 image data and send it to the server, and there I will convert it back to a JPEG image.
How can I so that? I already have a preview function that created a preview, but also create a base64 image:
function previewFile() {
var preview = document.querySelector('.uploadimage');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.addEventListener("load", function () {
preview.src = reader.result;
}, false);
if (file) {
reader.readAsDataURL(file);
}
}
I see many question people asking how to upload image to the server. I want to stay with the current configuration but just pass the base64 image data to the server as a string. I see many developers struggling with that, and most of them just engine up creating a form in javascript and submitting like that.
Here is a recent way I did this:
string base64 = base64string.Substring(base64string.IndexOf(',') + 1);
byte[] imageData = Convert.FromBase64String(base64);
Image img;
using (var ms = new MemoryStream(imageData, 0, imageData.Length)) {
img = Image.FromStream(ms, true);
You will need:
using System.Drawing;
OR to simply convert to a jpg, use this:
File.WriteAllBytes("image.jpeg", Convert.FromBase64String(base64));
For sending the data I use the following JS:
function sendImage() {
if (this.files && this.files[0]) {
var FR = new FileReader();
FR.onload = function (e) {
$("#imgImage").attr("src", e.target.result); //show a preview
//send e.target.result as a string to your webservice
};
FR.readAsDataURL(this.files[0]);
}
}
I use this event to listen for uploaded files:
document.getElementById("fileid").addEventListener("change", sendImage, false);
And the front end:
<input type="file" id="fileid" />
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>