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.
Related
I am trying to make a facebook like image uploader with the most basic methods. I select the multiple images on the input and then it creates the per file progress bars with names. It shows it's loading but it doesn't send to the upload.php file. I have the HTML code section:
<div class="container">
<h1>Uploader</h1>
<hr>
<form action="#" id="image_form">
<input type="file" id='image' name="image" multiple>
</form>
<div class="container">
<div class="filelist">
</div>
<ul id="uploads">
</ul>
</div>
Then I have my javascript. The progress bars get created with the file names and the progress is tracked. I have tried it with largish files and it does take a long while to upload. Progress bar shows this accurately.
$('#image').change(function (event) {
var files = this.files;
// iterate over each file to upload, send a request, and attach progress event
for (var i = 0, file; file = files[i]; i++) {
var li = $("<li>" + file.name + "<div class='progress progress-striped active'><div class='progress-bar' style='width:0%'>" + file.size + "</div></div></li>");
// add the LI to the list of uploading files
$("#uploads").append(li);
// fade in the LI instead of just showing it
li.hide().fadeIn();
var xhr = new XMLHttpRequest();
xhr.upload.li = li;
xhr.upload.addEventListener('progress', function(e) {
var percent = parseInt(e.loaded / e.total * 100);
this.li.find(".progress-bar").width(percent+'%');
}, false);
// setup and send the file
xhr.open('POST', 'upload.php', true);
xhr.setRequestHeader('X-FILE-NAME', file.name);
xhr.send(file);
}
});
I have been struggling with this piece of code for the last week and have been through almost every topic on this site without success. Please could someone help me figure out why I can't post the file details to the php script.
I'm using this code to post files to PHP:
function postFile(action, file, postFileName) {
var fPostName = typeof postFileName === 'undefined' ? 'file' : postFileName;
/* Create a FormData instance */
var formData = new FormData();
/* Add the file */
formData.append(fPostName, file);
var requestUrl = rootUrl + action;
return new Promise(function (resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('POST', requestUrl);
/* handlers */
xhr.onload = function () {
if (this.status >= 200 && this.status < 300) {
resolve(xhr.response);
} else {
reject({
status: this.status,
statusText: xhr.statusText
});
}
};
xhr.onerror = function () {
reject({
status: this.status,
statusText: xhr.statusText
});
};
console.log(formData);
/* send request */
xhr.send(formData);
});
}
// Sample usage
* <<< FILE upload >>>>>>
* var file = document.getElementById('f').files[0];
* console.log(file);
* postFile('your_processing_script.php', file).then(function (response) {
* console.log(response);
* },function (er) {
* console.log(er);
* });
and then in PHP you should have:
$_FILES["file"] or $_FILES[postFileName]
Hope this helps you.
Cheers
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>
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.
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>
I am developing a website in HTML, javascript & jQuery. I want to upload images to amazon s3 server in an ajax request. There is no such SDK to integrate s3 in Javascript. A PHP SDK is available, but it is not useful to me. Can anybody provide solution to this in javascript?
Got Amazon S3 & CORS working on js and html5 using XMLHTTPObject based on this article article.
1: CORS only works from a proper URL "http://localhost". (file///xyz will make you go insane)
2 : Make sure you got the POLICY and Secret compiled correctly - here is my policy and this is the link you can get the project to get you started with Signature and Policy -- do not publish this JS with your Secret EVER!
POLICY_JSON = { "expiration": "2020-12-01T12:00:00.000Z",
"conditions": [
{"bucket": this.get('bucket')},
["starts-with", "$key", ""],
{"acl": this.get('acl')},
["starts-with", "$Content-Type", ""],
["content-length-range", 0, 524288000]
]
};
var secret = this.get('AWSSecretKeyId');
var policyBase64 = Base64.encode(JSON.stringify(POLICY_JSON));
console.log ( policyBase64 )
var signature = b64_hmac_sha1(secret, policyBase64);
b64_hmac_sha1(secret, policyBase64);
console.log( signature);
Here is the JS code
function uploadFile() {
var file = document.getElementById('file').files[0];
var fd = new FormData();
var key = "events/" + (new Date).getTime() + '-' + file.name;
fd.append('key', key);
fd.append('acl', 'public-read');
fd.append('Content-Type', file.type);
fd.append('AWSAccessKeyId', 'YOUR ACCESS KEY');
fd.append('policy', 'YOUR POLICY')
fd.append('signature','YOUR SIGNATURE');
fd.append("file",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', 'https://<yourbucket>.s3.amazonaws.com/', true); //MUST BE LAST LINE BEFORE YOU SEND
xhr.send(fd);
}
Helper functions
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("Done - " + evt.target.responseText );
}
function uploadFailed(evt) {
alert("There was an error attempting to upload the file." + evt);
}
function uploadCanceled(evt) {
alert("The upload has been canceled by the user or the browser dropped the connection.");
}
Then the HTML Form
<form id="form1" enctype="multipart/form-data" method="post">
<div class="row">
<label for="file">Select a File to Upload</label><br />
<input type="file" name="file" id="file" onchange="fileSelected()"/>
</div>
<div id="fileName"></div>
<div id="fileSize"></div>
<div id="fileType"></div>
<div class="row">
<input type="button" onclick="uploadFile()" value="Upload" />
</div>
<div id="progressNumber"></div>
Happy CORS-ing!
Amazon just allowed Cross-Origin Resource Sharing, in theory it allows your users to upload to S3 directly, without using your server (and PHP) as a proxy.
Heres the docs -> http://docs.amazonwebservices.com/AmazonS3/latest/dev/cors.html
They do a great job of telling you how to enable it on an S3 bucket, but iv found no actual javascript examples of how to get data from client to bucket.
First person to post CORS.js is a legend xD
You can do this by AWS S3 Cognito try this link here :
http://docs.aws.amazon.com/AWSJavaScriptSDK/guide/browser-examples.html#Amazon_S3
Also try this code
Just change Region, IdentityPoolId and Your bucket name
<!DOCTYPE html>
<html>
<head>
<title>AWS S3 File Upload</title>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1.12.min.js"></script>
</head>
<body>
<input type="file" id="file-chooser" />
<button id="upload-button">Upload to S3</button>
<div id="results"></div>
<script type="text/javascript">
AWS.config.region = 'your-region'; // 1. Enter your region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'your-IdentityPoolId' // 2. Enter your identity pool
});
AWS.config.credentials.get(function(err) {
if (err) alert(err);
console.log(AWS.config.credentials);
});
var bucketName = 'your-bucket'; // Enter your bucket name
var bucket = new AWS.S3({
params: {
Bucket: bucketName
}
});
var fileChooser = document.getElementById('file-chooser');
var button = document.getElementById('upload-button');
var results = document.getElementById('results');
button.addEventListener('click', function() {
var file = fileChooser.files[0];
if (file) {
results.innerHTML = '';
var objKey = 'testing/' + file.name;
var params = {
Key: objKey,
ContentType: file.type,
Body: file,
ACL: 'public-read'
};
bucket.putObject(params, function(err, data) {
if (err) {
results.innerHTML = 'ERROR: ' + err;
} else {
listObjs(); // this function will list all the files which has been uploaded
//here you can also add your code to update your database(MySQL, firebase whatever you are using)
}
});
} else {
results.innerHTML = 'Nothing to upload.';
}
}, false);
function listObjs() {
var prefix = 'testing';
bucket.listObjects({
Prefix: prefix
}, function(err, data) {
if (err) {
results.innerHTML = 'ERROR: ' + err;
} else {
var objKeys = "";
data.Contents.forEach(function(obj) {
objKeys += obj.Key + "<br>";
});
results.innerHTML = objKeys;
}
});
}
</script>
</body>
</html>
If needed you can use github Link
I hope it will help others :)
For the authentication part,
No php code, no server, no large JS code except below;
you might use AWS Cognito IdentityPoolId as credential, less code
but you are required to create AWS Cognito IdetityPool and attach policy, simply s3 write access.
var IdentityPoolId = 'us-east-1:1...........';
AWS.config.update({
credentials: new AWS.CognitoIdentityCredentials({
IdentityPoolId: IdentityPoolId
})
});