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.
Related
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'm trying to get my app to both save in the server the resized image and the original file.
This is what I've tried so far:
HTML:
<a ng-model="originalPic"
ngf-select="uploadphototest($file)"
ngf-resize="{width: 1170, type: 'image/jpeg'}"
ngf-resize-if="$width > 1000"
ngf-model-options="{updateOn: 'change drop paste'}"
ngf-fix-orientation="true">
Upload image
</a>
JS:
$scope.uploadphototest = function (file) {
$scope.fileext = file.name.substring(file.name.lastIndexOf('.'), file.name.length);
$scope.uniqueportrait = $scope.fairnameonly + "-" + moment().format('DD-MM-YYYY-HH-mm-ss') + $scope.fileext;
Upload.imageDimensions(file).then(function(dimensions){
if (dimensions.width < 1170){
$scope.sizeerror = true;
}else{
fileor = $scope.originalPic;
Upload.upload({
url: 'uploadtest.php',
data: {
file: file,
name: Upload.rename(file, $scope.uniqueportrait),
fileor: fileor,
}
}).then(function (resp) {
...
});
};
});
};
And my PHP:
<?php
$filename = $_FILES['file']['name'];
$destination = '/home/clients/cc5399b00bc00f15dc81742a0369c7b8/discovery/register/uploadstest/' . $filename;
move_uploaded_file( $_FILES['file']['tmp_name'] , $destination );
$filenameor = "ORIGINAL".$_FILES['fileor']['name'];
$destinationor = '/home/clients/cc5399b00bc00f15dc81742a0369c7b8/discovery/register/uploadstest/' . $filenameor;
move_uploaded_file( $_FILES['fileor']['tmp_name'] , $destinationor );
?>
So far is going through but only uploading the resized one, the original one seems not to pass from the model to the function, as the model comes back undefined in the console...
What am I missing?
You could use the Upload.resize service of the library. Do not use ngf-resize andgf-resize-if in your HTML but resize the file in your JS. Something like:
HTML:
<a ng-model="originalPic"
ngf-select="uploadphototest($file)"
ngf-model-options="{updateOn: 'change drop paste'}"
ngf-fix-orientation="true">
Upload image
</a>
JS
$scope.uploadphototest = function (file) {
$scope.fileext = file.name.substring(file.name.lastIndexOf('.'), file.name.length);
$scope.uniqueportrait = $scope.fairnameonly + "-" + moment().format('DD-MM-YYYY-HH-mm-ss') + $scope.fileext;
Upload.imageDimensions(file).then(function(dimensions){
if (dimensions.width < 1170){
$scope.sizeerror = true;
} else if(dimensions.width > 1000){
var resizeOptions = {
width: 1170
};
Upload.resize(file, resizeOptions).then(function(resizedFile) {
uploadFile(file, resizedFile);
});
} else {
uploadFile(file, file);
}
});
};
function uploadFile(originalFile, resizedFile) {
Upload.upload({
url: 'uploadtest.php',
data: {
file: resizedFile,
fileor: Upload.rename(file, $scope.uniqueportrait), //This returns a file
}
}).then(function (resp) {
...
});
}
Here's a fiddle of something similar: JSFiddle
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>
I'm using this code to upload multiple files to imgur at once but its not working. It doesn't even trigger at all;
<form action="imgur.php" method="post" enctype="multipart/form-data">
Send these files:<br />
<input name="file[]" type="file" multiple="multiple" onchange="upload(this.files[0])" />
</form>
<?php
foreach ($_FILES['file']['tmp_name'] as $index => $tmpName) {
if( !empty( $tmpName ) && is_uploaded_file( $tmpName ) )
{
?>
<script type="text/javascript">
window.ondragover = function(e) {e.preventDefault()}
window.ondrop = function(e) {e.preventDefault(); upload(e.dataTransfer.files[0]); }
function upload(file) {
if (!file || !file.type.match(/image.*/)) return;
document.body.className = "uploading";
var fd = new FormData();
fd.append("image", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", "https://api.imgur.com/3/image.json");
xhr.onload = function() {
var code = JSON.parse(xhr.responseText).data.link + '\n';
var editor = eval('opener.' + 'clickableEditor');
editor.performInsert(code);
javascript:window.close()
}
xhr.setRequestHeader('Authorization', 'Client-ID [MY-CLIENT-ID]');
xhr.send(fd);
}
</script>
<?php
}
}
?>
The file name this code is pasted is named as imgur.php
Please help!