I'm new here and I'm sorry if i have posted this in the wrong place or anything.
What i want to implement is a text which displays percentage from 1%-100% which shows how much a file has been uploaded.
Right now, It shows just "Loading.." Instead of uploading..
I'm using PHP and JS in the website. Here is the script for the "Loading" button.
echo "<form id=\"uploads\" action=\"\" method=\"post\" enctype=\"multipart/form-data\"><input type=\"hidden\" value=\"myForm\" name=\"$upload_name\">
<center><input type=\"file\" value=\"Upload\" name=\"upload_file[]\" class=\"file\" multiple class=\"button2\"/> <br><br><input type=\"button\" id=\"upload\" class=\"button2\" value=\"Upload\" onclick=\"document.getElementById('upload').disabled = 'disabled'; document.getElementById('upload').value = 'Loading...'; document.getElementById('uploads').submit();\"><br><br></center>
</form></center>
";
How can i implement this? Please direct me to the path where i can implement this feature.
So a "without library" solution. Provide the URL of your server upload handler, select your file and click on upload. You should see the progression as a percentage.
document.querySelector("#upload").addEventListener("click",function(){
var oReq = new XMLHttpRequest();
oReq.addEventListener("progress", updateProgress, false);
oReq.addEventListener("load", transferComplete, false);
oReq.addEventListener("error", transferFailed, false);
oReq.addEventListener("abort", transferCanceled, false);
var upload_to_URL= document.querySelector("#upload_to").value;
oReq.open('POST', upload_to_URL , true);
var formData = new FormData();
formData.append("upload", file.files[0]);
oReq.send(formData);
});
// progress on transfers from the server to the client (downloads)
function updateProgress (oEvent) {
if (oEvent.lengthComputable) {
var percentComplete = oEvent.loaded / oEvent.total;
// ...
document.querySelector("#upload-progress").innerHTML= (percentComplete * 100 ) + "%"
} else {
// Unable to compute progress information since the total size is unknown
}
}
function transferComplete(evt) {
document.querySelector("#upload-progress").innerHTML= " <span style='color:green'>100%</span>";
}
function transferFailed(evt) {
alert("An error occurred while transferring the file.");
}
function transferCanceled(evt) {
alert("The transfer has been canceled by the user.");
}
<form id="upload-form">
<input type="text" id="upload_to" placeholder="Upload handler URL"/><br />
<input type="file" id="file"/>
<input type="submit" value="upload" id="upload" />
</form>
<div id="upload-progress"></div>
Related
I have a JSP page with <form> that uploads a file on submit.
But the upload function is not uploading any file to the server at the path /uploads.
HTML form:
<form action="./index.jsp" onsubmit="uploadFile()">
<input type="file" class="form-control-file " placeholder="Choose file" id="excelInput">
<button type="submit" class="btn btn-primary">Run Profiling</button>
</form>
Javascript function to upload file:
<script>
function uploadFile(){
let excel = document.getElementById("excelInput").files[0]; // file from input
alert(excel);
let req = new XMLHttpRequest();
let formData = new FormData();
try{
formData.append("excel", excel);
req.open("POST", 'D:\\eclipse\\workspace\\Project2\\WebContent\\uploads');
req.send(formData);
}
catch(e){
alert(e);
}
}
</script>
It is not going to the catch() section. But it isn't uploading either.
Is there anything missing ?
The dupes seems to be very poor, so I post an answer.
You basically want to add an eventListener AND submit to a WEB SERVICE! Not a file location
window.addEventListener("load", function() {
document.getElementById("uploadForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop the submit
let excel = document.getElementById("excelInput").files[0]; // file from input
let req = new XMLHttpRequest();
let formData = new FormData();
try {
formData.append("excel", excel);
req.open("POST", 'actual web address of a process that can handle xmlhttprequests');
req.send(formData);
} catch (e) {
console.log(e);
}
})
})
<form action="./index.jsp" id="uploadForm">
<input type="file" class="form-control-file " placeholder="Choose file" id="excelInput">
<button type="submit" class="btn btn-primary">Run Profiling</button>
</form>
I am attempting to read the camera using HTML5 and XMLHttpRequest. I have tried a couple of things but no matter what I change I can not seem to actually send the Form Data, data through the post. So can someone tell me where I am making the error and not generating any image to save. Alternatively if you don't have to call out to a url but instead use a local function that would be awesome.
aspx file and the HTML structure.
<!-- CAMERA UPLOAD -->
<div class="row" runat="server" id="div_Upload" visible="false">
<hr />
<label for="fileToUpload">Select a File to Upload</label><br />
<input type="file" name="fileToUpload" class="btn btn-shadow" id="fileToUpload" accept="image/*" capture="camera" onchange="fileSelected()" />
<input type="button" name="btn_upload" value="Upload" id="btn_upload" onclick="uploadFile()" class="btn btn-shadow" />
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div id="progressNumber"></div>
<hr />
</div>
The javascript in the head of the file:
<script type="text/javascript">
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
alert("fileSelected : " + file.name);
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
}
}
function uploadFile() {
var fd = new FormData();
var file = document.getElementById('fileToUpload').files[0]
alert("upload File : " + file.name);
fd.append(file.name, file);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "SaveToFile.aspx");
xhr.send(fd);
alert("xhr Response: " + xhr.response);
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
</script>
And here is the SaveToFile.aspx
<%# Page Language="C#" %>
<%
HttpFileCollection files = HttpContext.Current.Request.Files;
for (int index = 0; index < files.Count; index++)
{
HttpPostedFile uploadfile = files[index];
uploadfile.SaveAs(Server.MapPath(".") + "\\upload\\" + uploadfile.FileName);
}
HttpContext.Current.Response.Write("Upload successfully!");
%>
By the time I am calling the SaveToFile.aspx page there are no files sent and the file count = 0;
Any help would be greatly appreciated! And a way to keep within the same page would be awesome. I saw a reference to that in another post but when I call a local function, I get a 404 error.
With asp.net and webforms, the form information was incomplete.
I went from
<form>
on the site master page to
<form id="form1" runat="server" enctype="multipart/form-data">
This fixed all issues and several different options to get data from client side, fixed themselves once I made the change.
With a master page I don't know of a different way to resolve this but this works with the site master.
i have a form , there is an input type file , that element has a button with a on click event calling a function to upload the file (image), after that user has filled all his data hit the button validate ,
i want to clear the input type file once the user has clicked upload file and file has been uploaded , because what happening is that file to be uploaded to the server it takes time when the user hit upload file and also when he clicks validate button because it's passing in http request as an element of the form so what i want is to remove the file from the input once it is uploaded , this is my code i tested different scenarios none of them has worked.
<div>
<input type='file' name='img1' id='img1'>
<input type="button" value="upload" onclick="uploadFile()">
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
</div>
js
function _(el){
return document.getElementById(el);
}
function uploadFile(){
var file = _("img1").files[0];
var e = document.getElementById("img1");
var formdata = new FormData();
formdata.append("img1", file);
var ajax = new XMLHttpRequest();
ajax.upload.addEventListener("progress", progressHandler, false);
ajax.addEventListener("load", completeHandler, false);
ajax.addEventListener("error", errorHandler, false);
ajax.addEventListener("abort", abortHandler, false);
ajax.open("POST", 'distination');
ajax.send(formdata);
formdata.delete("img1");
formdata = '';
_("img1").files[0] = '';
e.value ='';
$('#img1').val('');
$('#img1')[0].reset();
}
the action of the form is PHP_SELF
I found this by searching StackOverflow for what you are specifically trying to do:
function resetForm($form) {
$form.find('input:file').val('');
}
// to call, use:
resetForm($('#myform'));
This solution was derived entirely from Resetting a multi-stage form with jQuery
Example usage when you submit the form would be:
$('#validateButton').click(function (e) {
e.preventDefault();
resetForm($('#myform'));
$('#myform').submit();
});
Where #validateButton and #myform should be replaced with the actual names of your DOM elements.
When a user uploads a picture to a server, the picture must to be stored like pkUsre.extention, exemple 1.jpg, where the number 1 is the users primary key.
I have the follow code that works fine to upload the file, but I dont know how to send the pkUser to server with the picture. Any idea how to do that?
//Html code
<form id="form1" enctype="multipart/form-data" method="post" >
<div class="row">
<input type="file" name="fileToUpload" id="fileToUpload" onchange="fileSelected();"/>
</div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
<input type="button" id="btnSd" value="Upload" />
</div>
<div id="progressNumber"></div>
</form>
//PHP code
if ( move_uploaded_file( $_FILES['fileToUpload']['tmp_name'], "pic/". basename($_FILES['fileToUpload']['name']) ) ) {
echo basename($_FILES['fileToUpload']['name']);
}
else {
echo "There was a problem uploading your file - please try again.";
}
//Javascript code
<script type="text/javascript">
function fileSelected() {
var file = document.getElementById('fileToUpload').files[0];
if (file) {
var fileSize = 0;
if (file.size > 1024 * 1024)
fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
else
fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
}
}
function uploadFile() {
var fd = new FormData();
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", uploadProgress, false);
xhr.addEventListener("load", uploadComplete, false);
xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false);
xhr.open("POST", "uploadFoto.php");
xhr.send(fd);
}
function uploadProgress(evt) {
if (evt.lengthComputable) {
var percentComplete = Math.round(evt.loaded * 100 / evt.total);
document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
}
else {
document.getElementById('progressNumber').innerHTML = 'unable to compute';
}
}
function uploadComplete(evt) {
/* This event is raised when the server send back a response */
alert(evt.target.responseText);
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file.");
}
function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
</script>
<script type="text/javascript">
$(document).on("click", "#btnSd", function(){
uploadFile();
});
</script>
only file uplod name in server database and move to file in folder user_post.
file copy in filder and only name is database save.
function getuniqkey($special='')
{
return md5(date("Y-m-d H:i:s").uniqid(rand(), true).time().$special);
}
if(isset($_FILES["fileToUpload"]))
{
$tmp_name = $_FILES["fileToUpload"]["tmp_name"];
$name1 = $_FILES["fileToUpload"]["name"];
$datasheet_new_name=getuniqkey($tmp_name).substr($name1,strrpos($name1,"."));
if(copy($_FILES["fileToUpload"]["tmp_name"], "user_post/".$datasheet_new_name))
{
$file_name = "http://domain name.com/user_post/{$datasheet_new_name}";
}
else
{
echo'user file not upload.';
}
}
echo $file_name;
Finally I developed a solution.
Add a class "fileUpload" to the input element that will hold the file to be uploaded.
Set a id as something-pkUser. I sit id="fileUpload-1" dynamically created whit php.
Make a little change on the javascript code above. Go to the function uploadFile() and create a parameter "n". It will be like that uploadFile(n).
Inside this function go to the fd.append(...,...) part and change the first an second parameter 'fileToUpload' for "n", you have created. You will have the follow:
fd.append("fileToUpload", document.getElementById('fileToUpload').files[0]);
changed by this:
fd.append(n, document.getElementById(n).files[0]);
Now you must change jquery code:
before was that:
$(document).on("click", "#btnSd", function(){
uploadFile();
});
Now will be like that:
$(document).on("click", "#btnSd", function(){
uploadFile($(".fileToUpload").attr('id'));
});
And finally, ajax will send will send data to server. We can clear the string with php substrigs functions. This was my solution:
foreach ($_FILES as $key => $value) {
$arrFile = $key;
$pkUser = substr($arrFile,(int)$pos=strpos($arrFile, "-")+1);
$filename=$_FILES[$arrFile]['name'];
$ext = substr($filename,strpos($filename, "."));
}
$finalName=$pkUser.$ext;
if ( move_uploaded_file( $_FILES[$arrFile]['tmp_name'], "pic/".$finalName ) ) {
echo $finalName;
}
else {
echo "There was a problem uploading your file - please try again.";
}
Finally this works good! I can send the user's primary key and store as I want.
Hello I have encountered a problem while coding in Javascript and PHP (Ajax non jquery). I am trying to upload a file over Ajax, and handle it in PHP.
This is my code:
index.html
<html>
<head>
<title>PHP AJAX Upload</title>
<script type="text/javascript">
function upload() {
// 1. Create XHR instance - Start
var dat= "bla";
document.getElementById("div2").innerHTML = "working";
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
var rad = document.getElementById('fajl');
var filee = rad.files[0];
var formData = new FormData();
formData.append('rad',filee)
formData.append('var',dat)
xhr.open('POST', 'upload.php');
xhr.send(formData);
xhr.onload = function () {
if (xhr.readyState === 4 && xhr.status == 200) {
document.getElementById("div2").innerHTML = xhr.responseText;
//alert(xhr.readyState);
//alert(xhr.status);
}
}
}
</script>
</head>
<body>
<form id="uploadForm" enctype="multipart/form-data">
<label>Upload File:</label><br/>
<input name="rad" id="fajl" type="file" class="inputFile" />
<input type="submit" value="Submit" class="btnSubmit" onclick="upload()" />
<div id="div2">
</div>
</form>
</body>
</html>
upload.php
<?php
if(is_array($_FILES)) {
if(is_uploaded_file($_FILES['rad']['tmp_name'])) {
$sourcePath = $_FILES['rad']['tmp_name'];
$targetPath = "images/".$_FILES['rad']['name'];
if(move_uploaded_file($sourcePath,$targetPath)) {
echo ("uspjeh<br>");
}}
}
$podatak=$_POST['var'];
echo "$podatak"
?>
Problem is that I dont see PHP script response in my div2 element. Ajax behaves wierd and it puzzles me. I have put JavaScript alert command under xhr.readyState condition (now commented). When I do that then I see the output, but when I close alert dialog, the browser automaticly reloads page and makes the URL like i'm using GET method (i'm using POST) and then server output dissapears. (rad in ?rad=... is the name of my input element)
When I'm not using alert command then I don't see output at all, because page redirects really fast. What am I misiing?
It's because you are using a submit button and that's submitting the form. By default form methods are GET requests. Change to just a button instead:
<input type="button" value="Submit" class="btnSubmit" onclick="upload()" />
The default form action (submitting) is being carried out.
To stop this add return false to your click handler:
onclick="upload(); return false;"