I have a page in which I'm uploading an image using from input type=file to an image tag using this code
$('#profile-image-upload').change( function(event) {
var path = URL.createObjectURL(event.target.files[0]);
$("#image").attr('src',URL.createObjectURL(event.target.files[0]));
This gives me an bolb data of path like this blob:http://localhost:8080/467d02c9-0af0-448a-a239-69e8d4037dd1. My image is in this blob data saved in path variable
Now I also want this image file to save in my server directory and I'm use ajax to send it to my server
var ajax;
if (window.XMLHttpRequest) // For modren Browsers
ajax=new XMLHttpRequest();
else
ajax=new ActiveXObject("Microsoft.XMLHTTP"); // For IE5 & IE8
ajax.open("POST","../UploadImg.php",true);
ajax.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var data= "path="+path+"&type="+user+"&id="+id+"&extent="+extent;
//path = blob data
//user = user name
//id = user id
//extent = extension of image
ajax.onreadystatechange=function()
{
if (ajax.readyState==4 && ajax.status==200){
alert(ajax.responseText);
}
}
ajax.send(data);
});
and my server side coding is
$img_ff = $_POST["path"]; // blob path
$user = $_POST["type"];
$id = $_POST["id"];
$extension = $_POST["extent"];
$dst_img= $user.$id.".".$extention; // for example user17.png
$dst_path= "localhost:8080/live4others/images/";
$dst_cpl = $dst_path . $dst_img;
if(move_uploaded_file($dst_cpl, $img_ff)){
echo "yes";
}else{
echo "error";
}
if( file_put_contents( $img_ff, $dst_cpl)){
echo "yes";
}else{
echo "error";
}
both of the methods are not working. Please tell me where I'm doing wrong. They give error and says given path is invalid.
You can try this. I'm using same but using blob to simply preview the images/videos before submitting.
Jquery
$('#<formId>').on('submit', function(e) {
e.preventDefault();
$.ajax({
url: "../UploadImg.php",
type: "POST",
data: new FormData(this),
dataType: "json",
contentType: false,
cache: false,
processData:false,
success: function(response){
console.log(response);
},
error : function (jqXHR, textStatus, errorThrown) {
}
});
});
PHP - UploadImg.php
$tmpFile = $_FILES['<fileElementName>'];
$absolutePathOfdestinationFolder = '/var/www/<projectDocRoot>/images/'.$user.$id.".".$extention;
if(move_uploaded_file($tmpFile['tmp_name'], $absolutePathOfdestinationFolder)){
echo "yes";
}else{
echo "error";
}
Related
I am trying to upload a file to the same place in the server, The file is a html file the is created through javascript. I currently have it set up so I am able to create and download the file (Contents is equal to some text) This part works. I am trying to make it so that on button press instead of the page providing me a link to download the file, the file gets upload to a folder on the webserver.
The text file is made with the following code:
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
return textFile;
};
link.href = makeTextFile(contents);
This is the Ajax code:
var form_data = new FormData();
form_data.append("file", textFile);
$.ajax({
url:"upload.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
console.log("File Uploading");
},
success:function(data)
{
console.log("File Uploaded: " + data);
}
});
upload.php
if($_FILES["file"]["name"] != '')
{
$test = explode('.', $_FILES["file"]["name"]);
$ext = end($test);
$name = rand(100, 999) . '.' . $ext;
$location = '/uploads/' . $name;
move_uploaded_file($_FILES["file"]["tmp_name"], $location);
echo '<img src="'.$location.'" height="150" width="225" class="img-thumbnail" />';
}
?>
Thanks :)
So i have a jspdf script im working with.
.save works as expected and outputs the image + text elements.
How ever
doc.output() = only text
doc.output('datauristring') = corrupted pdf
I think im missing something
here is an example of my code
var imgData = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQIAdgB2AAD/examplestringonly...';
var doc = new jsPDF('p', 'pt');
doc.text(35, 340, "data notes");
doc.addImage(imgData, 'JPEG', 350, 40, 200, 40);
doc.output('datauristring');
Solved hope this helps anyone.
.output() was correctly sending all the date, how ever the base64 was being corrupted. so i made the php handle the datauri, and used base64_decode() on it.
then made it save to file.
fixes the issues completely.
var pdf = doc.output('datauri');
var data = new FormData();
data.append("data" , pdf);
data.append("id" , id);
$.ajax({
url: 'upload.php',
data: data,
dataType: 'text',
processData: false,
contentType: false,
type: 'POST',
success: function (response) {
console.log('Exit to send request');
},
error: function (jqXHR) {
console.log('Failure to send request');
}
});
<?php
if(!empty($_POST['data'])){
$data = str_replace(' ','+',$_POST['data']);
$data = substr($imgData,strpos($imgData,",")+1);
$data = base64_decode($imgData);
$id = $_POST['id'];
$fname = "test.pdf"; // name the file
$file = fopen("api/warranty/pdf/" .$id, 'w'); // open the file path
fwrite($file, $data); //save data
fclose($file);
} else {
echo "No Data Sent";
}
I want to implement a simple file upload in my intranet-page, with the smallest setup possible.
This is my HTML part:
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload">Upload</button>
and this is my JS jquery script:
$("#upload").on("click", function() {
var file_data = $("#sortpicture").prop("files")[0];
var form_data = new FormData();
form_data.append("file", file_data);
alert(form_data);
$.ajax({
url: "/uploads",
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(){
alert("works");
}
});
});
There is a folder named "uploads" in the root directory of the website, with change permissions for "users" and "IIS_users".
When I select a file with the file-form and press the upload button, the first alert returns "[object FormData]". the second alert doesn't get called and the"uploads" folder is empty too!?
Can someone help my finding out whats wrong?
Also the next step should be, to rename the file with a server side generated name. Maybe someone can give me a solution for this, too.
You need a script that runs on the server to move the file to the uploads directory. The jQuery ajax method (running on the client in the browser) sends the form data to the server, then a script running on the server handles the upload.
Your HTML is fine, but update your JS jQuery script to look like this:
(Look for comments after // <-- )
$('#upload').on('click', function() {
var file_data = $('#sortpicture').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
alert(form_data);
$.ajax({
url: 'upload.php', // <-- point to server-side PHP script
dataType: 'text', // <-- what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert(php_script_response); // <-- display response from the PHP script, if any
}
});
});
And now for the server-side script, using PHP in this case.
upload.php: a PHP script that is located and runs on the server, and directs the file to the uploads directory:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
Also, a couple things about the destination directory:
Make sure you have the correct server path, i.e., starting at the PHP script location what is the path to the uploads directory, and
Make sure it's writeable.
And a little bit about the PHP function move_uploaded_file, used in the upload.php script:
move_uploaded_file(
// this is where the file is temporarily stored on the server when uploaded
// do not change this
$_FILES['file']['tmp_name'],
// this is where you want to put the file and what you want to name it
// in this case we are putting in a directory called "uploads"
// and giving it the original filename
'uploads/' . $_FILES['file']['name']
);
$_FILES['file']['name'] is the name of the file as it is uploaded. You don't have to use that. You can give the file any name (server filesystem compatible) you want:
move_uploaded_file(
$_FILES['file']['tmp_name'],
'uploads/my_new_filename.whatever'
);
And finally, be aware of your PHP upload_max_filesize AND post_max_size configuration values, and be sure your test files do not exceed either. Here's some help how you check PHP configuration and how you set max filesize and post settings.
**1. index.php**
<body>
<span id="msg" style="color:red"></span><br/>
<input type="file" id="photo"><br/>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','#photo',function(){
var property = document.getElementById('photo').files[0];
var image_name = property.name;
var image_extension = image_name.split('.').pop().toLowerCase();
if(jQuery.inArray(image_extension,['gif','jpg','jpeg','']) == -1){
alert("Invalid image file");
}
var form_data = new FormData();
form_data.append("file",property);
$.ajax({
url:'upload.php',
method:'POST',
data:form_data,
contentType:false,
cache:false,
processData:false,
beforeSend:function(){
$('#msg').html('Loading......');
},
success:function(data){
console.log(data);
$('#msg').html(data);
}
});
});
});
</script>
</body>
**2.upload.php**
<?php
if($_FILES['file']['name'] != ''){
$test = explode('.', $_FILES['file']['name']);
$extension = end($test);
$name = rand(100,999).'.'.$extension;
$location = 'uploads/'.$name;
move_uploaded_file($_FILES['file']['tmp_name'], $location);
echo '<img src="'.$location.'" height="100" width="100" />';
}
Use pure js
async function saveFile()
{
let formData = new FormData();
formData.append("file", sortpicture.files[0]);
await fetch('/uploads', {method: "POST", body: formData});
alert('works');
}
<input id="sortpicture" type="file" name="sortpic" />
<button id="upload" onclick="saveFile()">Upload</button>
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending
async function saveFile(inp)
{
let user = { name:'john', age:34 };
let formData = new FormData();
let photo = inp.files[0];
formData.append("photo", photo);
formData.append("user", JSON.stringify(user));
try {
let r = await fetch('/upload/image', {method: "POST", body: formData});
console.log('HTTP response code:',r.status);
alert('success');
} catch(e) {
console.log('Huston we have problem...:', e);
}
}
<input type="file" onchange="saveFile(this)" >
<br><br>
Before selecting the file Open chrome console > network tab to see the request details.
<br><br>
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
var formData = new FormData($("#YOUR_FORM_ID")[0]);
$.ajax({
url: "upload.php",
type: "POST",
data : formData,
processData: false,
contentType: false,
beforeSend: function() {
},
success: function(data){
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
and this is the php file to receive the uplaoded files
<?
$data = array();
//check with your logic
if (isset($_FILES)) {
$error = false;
$files = array();
$uploaddir = $target_dir;
foreach ($_FILES as $file) {
if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
$files[] = $uploaddir . $file['name'];
} else {
$error = true;
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
}
echo json_encode($data);
?>
I have looked into the best way to do this and keep getting conflicting information and advice on the various demonstrations.
My code is as follows...
html
<img src="http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=265&d=identicon&r=PG" style="border: thin solid #999999;"/>
<p>Change<span class="pull-right">Powered by Gravatar</span></p>
<input type="file" name="avatar-uploader" id="avatar-uploader" style="display: none;" />
javascript
$('input[type=file]').on('change', function(){
$.ajax({
url: "/ajax/upload-new-avatar.ajax.php", // Url to which the request is send
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false, // To send DOMDocument or non processed data file it is set to false
success: function(data) // A function to be called if request succeeds
{
alert("Success");
}
});
});
PHP: /ajax/upload-new-avatar.ajax.php
error_reporting(E_ALL);
ini_set('display_errors', 1);
session_start();
$sourcePath = $_FILES['avatar-uploader']['tmp_name']; // Storing source path of the file in a variable
$targetPath = "".$_FILES['avatar-uploader']['name']; // Target path where file is to be stored
move_uploaded_file($sourcePath,$targetPath) ; // Moving Uploaded file
I'm sure there is something simple that I am missing here and i'm going to feel pretty stupid afterwards but could someone explain to me why the image isn't being uploaded to the server and saved in the AJAX directory for further processing.
What I need it to do is when the user clicks on the "change" hyperlink below the image it opens a file upload dialog (working), once an image has been selected it automatically uploads to the server over an AJAX connection (possibly working, logging shows the PHP file is being triggered), and then the image file needs to be saved in the AJAX directory to be further processed later in the code for it to be uploaded to the avatar service.
Thanks in advance.
Have managed to get it working...
Here is my amended code...
Javascript
$('input[type=file]').on('change', function(event){
files = event.target.files;
event.stopPropagation(); // Stop stuff happening
event.preventDefault(); // Totally stop stuff happening
$("#avatar-status").text("Loading new avatar...");
$("#avatar").css("opacity", "0.4");
$("#avatar").css("filter", "alpha(opacity=40);");
//Create a formdata object and add the files
var data = new FormData();
$.each(files, function(key, value) {
data.append(key, value);
});
$.ajax({
url: '/ajax/upload-new-avatar.ajax.php?files',
type: 'POST',
data: data,
cache: false,
dataType: 'json',
processData: false, // Don't process the files
contentType: false, // Set content type to false as jQuery will tell the server its a query string request
success: function(data, textStatus, jqXHR) {
if(typeof data.error === 'undefined') {
//Success so call function to process the form
//submitForm(event, data);
$("#avatar-status").text("Powered by Gravatar");
$("#avatar").css("opacity", "");
$("#avatar").css("filter", "");
} else {
//Handle errors here
alert('ERRORS: ' + textStatus);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//Handle errors here
alert('ERRORS: ' + textStatus);
}
});
});
PHP
session_start();
require_once("../libraries/logging.lib.php");
new LogEntry("AJAX Upload Started - UploadNewAvatar", Log::DEBUG, "AvatarUpload");
sleep(3);
$data = array();
if(isset($_GET['files'])) {
$error = false;
$files = array();
$uploaddir = '../tmp/';
foreach($_FILES as $file) {
if(move_uploaded_file($file['tmp_name'], $uploaddir .basename($file['name']))) {
$files[] = $uploaddir .$file['name'];
new LogEntry("UploadNewAvatar - Upload Successful", Log::DEBUG, "AvatarUpload");
} else {
$error = true;
new LogEntry("UploadNewAvatar - Errors Occured", Log::ERROR, "AvatarUpload");
}
}
$data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
} else {
$data = array('success' => 'Form was submitted', 'formData' => $_POST);
new LogEntry("UploadNewAvatar - Form was submitted successfully", Log::DEBUG, "AvatarUpload");
}
echo json_encode($data);
HTML
<img id="avatar" src="http://www.gravatar.com/avatar/205e460b479e2e5b48aec07710c08d50?s=265&d=identicon&r=PG" style="border: thin solid #999999;"/>
<p>Change<span id="avatar-status" class="pull-right">Powered by Gravatar</span></p>
<input type="file" name="upfile" id="upfile" style="display: none;" />
This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 8 years ago.
i created a form. Thats shown below...
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#sbt").click(function(){
var re=$("#file").val();
$.ajax({
type: "POST",
url: "loadajax.php",
data: $("#data").serialize()+ '&photo=' +re,
success: function(data) {
$("#datas").html(data);
},
error: function(){
alert('error handing here');
}
});
});
});
</script>
Ajax response page
<?php
echo "<pre>";
print_r($_POST);
var_dump($_FILES);
?>
All input values are returned.but file is not uploaded.I don't know how to upload file using ajax. Please help me...
Try This
$("#sbt").click(function(){
var pht = $("#ph").val();
var str2 = "your_folder/"; // destination folder, if needed
var upvid = str2.concat(pht);
var data = new FormData();
data.append( 'photo', $('#photo')[0].files[0] );
data.append( 'pht', pht );
$.ajax({
type: "POST",
url: "loadajax.php",
processData: false,
contentType: false,
cache:true,
data: data,
success: function(data){
$("#datas").html(data
} ,
error: function(){
alert('error handing here');
}
});
});
<?php
$a = $_POST['pht'];
$file = str_replace( "\\", '/', $a );
$ofile = basename($file);
?>
You have to use a plugin for this, jQuery doesn't support this out of the box. The best know plugin is ajaxForm
This will post the form to the given url in the form action field using ajax. There are events available to add validations and post-submit funcions.
you can also do like this:
function upload() {
// id of the form "documentUploadForm"
var form = document.getElementById("documentUploadForm");
var formData = new FormData(form);
var xhr = new XMLHttpRequest();
var url = '<c:url value="/loadajax.php"/>';
xhr.open('POST', url, true);
xhr.onload = function(e) {
if (xhr.status === 200) {
outputData = JSON.parse(xhr.responseText);
console.log("Response:" +outputData);
}
};
xhr.send(formData);
}