Upload file XMLHttpRequest not working - javascript

I am trying to upload file with ajax it does not work for some reason, can you see what's up?
function upload(myform)
var file = this.files[0];
var formData = new FormData();
formData.append("material_file", document.getElementById("myfile"));
xmlhttp = new XMLHttpRequest();
xmlhttp.addEventListener('progress', function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xmlhttp progress: ' + (Math.floor(done/total*1000)/10) + '%');
}, false);
if ( xmlhttp.upload ) {
xmlhttp.upload.onprogress = function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xmlhttp.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
};
}
xmlhttp.onreadystatechange = function(e) {
if ( 4 == this.readyState ) {
console.log(['xmlhttp upload complete', e]);
}
};
xmlhttp.open('post', process_pdf.php, true);
xmlhttp.setRequestHeader("Content-Type","multipart/form-data");
xmlhttp.send(formData);
}
<form onsubmit="upload(this)">
<input type="file" name="myfile">
</form>
When I browse to the file and click submit I get error

According to the error, you need to create a myForm variable before you use it.
However, your larger problem is that one can't upload files with AJAX alone. Try using a library like SWFupload.
If you don't want to use Flash or another plugin, you'll need to skip the AJAX and work straight with POST.
<form method="post" enctype="multipart/form-data" action="/PATH/TO FILE">
<input type="file" name="myfile">
<input type="submit" value="upload file">
</form>

Related

How to send data to server with javascript

I'm a good back dev, but have a huge problem at front. So, i have a form that download photo to send it to server.
<form name="Forma" id="photoForm" method="POST" enctype="multipart/form-data">
<input type="button" class="btn btn-secondary" name="btn_file" id="loadFileXml" value="Выбрать фото" onclick="document.getElementById('file').click();" />
<input type="file" id="file" style="display:none" name="photo" required accept="image/jpeg,image/png,image/gif " />
<button type="submit " class="btn btn-primary " hidden id="Test1">Проверить</button>
</form>
And here is a function that should send data to server, for getting JSON response (i'm not sure with it,
var fileuploadinit = function(){
$('#file').change(function(){
var pathwithfilename = $('#file').val();
var filename = pathwithfilename.substring(12);
console.log(this.value);
var reader = new FileReader();
reader.onload = function(e) {
$('#blah').removeAttr("hidden");
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(file.files[0]);
});
};
$("#imgInp").change(function() {
readURL(this);
});
$(document).ready(function () {
fileuploadinit();
});
$('#file').on('change', function() {
if (this.value) {
console.log("Оппа, выбрали файл!");
console.log(this.value);
// $('#Test1').attr("disabled", "false")
$("#Test1").removeAttr("hidden");
$('#Test3123').attr("src", this.value);
$("#info").removeAttr("hidden");
} else { // Если после выбранного тыкнули еще раз, но дальше cancel
console.log("Файл не выбран");
}
})
var button = document.getElementById("Test1")
button.onclick = handleButtonClick;
function handleButtonClick() {
alert("Вы нажали на кнопку");
var xhr = new XMLHttpRequest();
var url = "/api/upload";
xhr.open("Post", url, true);
xhr.setRequestHeader("Content-type", "multipart/form-data");
xhr.setRequestHeader("Access-Control-Allow-Origin", "url/");
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 & xhr.status == 200){
var json = JSON.parse(xhr.responseText);
console.log(json.name);
}
};
var data = new FormData(photoForm)
xhr.send(data);
}
So, i spent on it for like 2 days, and absolutely don't know how to get photo from form to server. i tried literally everything, i think. It works, then i use action at html form method.

Sending data (image and some other parameters) to php by using javascript XMLHttpRequest

This code is proper working i can send username and imgtype with url and images send by using sendAsBinary function and get this data in php but issue is here two parameter username and imgtype that i'm sending with url that get by using GET Method but i want to get in POST method because i don't want to show in url box. I have try to send by using sendAsBinary function but not get in php just image get.
Please Help me i'm stuck on this from two days.
Thanks!
var xhr = new XMLHttpRequest();
var params = "username="+username+"&imgtype="+imgtype;
xhr.open('POST', upload_url+"?"+params, true);
var boundary = 'someboundary';
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
xhr.sendAsBinary(['--' + boundary, 'Content-Disposition: form-data; name="' + file_input_name + '"; filename="' + filename + '"', 'Content-Type: ' + type, '', data, '--' + boundary + '--','--' + boundary].join('\r\n'));
Using form data you can solve this problem
Follow this link click
A full working example is given below
HTML Code
<form enctype="multipart/form-data" method="post" name="fileinfo">
<label>Username:</label>
<input type="text" name="username" placeholder="username" required/>
<label>File to upload:</label>
<input type="file" name="userfile" required />
<input type="submit" value="submit form" />
</form>
<div></div>
Js code
var form = document.forms.namedItem("fileinfo");
form.addEventListener('submit', function(ev) {
var outputDiv = document.querySelector("div");
var dataSendToServer = new FormData(form);
var requestObject = new XMLHttpRequest();
requestObject.open("POST", "your_url", true);
requestObject.onload = function(event) {
if (requestObject.status == 200) {
alert(requestObject.responseText)
} else {
alert("Error " + requestObject.status + " occurred when trying to upload your file")
}
};
requestObject.send(dataSendToServer);
ev.preventDefault();
}, false);
PHP code
header("Access-Control-Allow-Origin: *");
$responseData=array('imgType'=>$_FILES['userfile']['type'],'username'=>$_POST['username']);
print_r(json_encode($responseData));

How to upload a file using javascript?

I want to create an uploader with js. Can anyone help me how to upload a file using javascript?
You can use html5 file type like this:
<input type="file" id="myFile">
You file will be in value:
var myUploadedFile = document.getElementById("myFile").files[0];
For more information see https://www.w3schools.com/jsref/dom_obj_fileupload.asp
and see example here: https://www.script-tutorials.com/pure-html5-file-upload/
You can upload files with XMLHttpRequest and FormData. The example below shows how to upload a newly selected file(s).
<input type="file" name="my_files[]" multiple/>
<script>
const input = document.querySelector('input[type="file"]');
input.addEventListener('change', (e) => {
const fd = new FormData();
// add all selected files
e.target.files.forEach((file) => {
fd.append(e.target.name, file, file.name);
});
// create the request
const xhr = new XMLHttpRequest();
xhr.onload = () => {
if (xhr.status >= 200 && xhr.status < 300) {
// we done!
}
};
// path to server would be where you'd normally post the form to
xhr.open('POST', '/path/to/server', true);
xhr.send(fd);
});
</script>
HTML Part:
<form enctype = "multipart/form-data" onsubmit="return false;" >
<input id="file" type="file" name="static_file" />
<button id="upload-button" onclick="uploadFile(this.form)"> Upload </button>
</form>
JavaScript Part:
function uploadFile(form){
const formData = new FormData(form);
var oOutput = document.getElementById("static_file_response")
var oReq = new XMLHttpRequest();
oReq.open("POST", "upload_static_file", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Uploaded!";
console.log(oReq.response)
} else {
oOutput.innerHTML = "Error occurred when trying to upload your file.<br \/>";
}
};
oOutput.innerHTML = "Sending file!";
console.log("Sending file!")
oReq.send(formData);
}
In the above HTML, I'm using the form to capture the files and calling the JS function when the button is clicked. In the JS function, I'm using the XMLHttpRequest to send the file.
A detailed step-by-step document can be found here.

HTML5 Camera Image XMLHttpRequest file is empty

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.

show loading percentage text in php

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>

Categories