I'm running into an issue using move_uploaded_file, specifically that it... doesn't work.
I have an input to upload the pdf:
<div>
Upload Resources
<input type="text" id="doc-name" name="doc-name">
<input type="file" id="doc-upload" name="doc-upload" accept="application/pdf">
<button id="upload-button">Upload</button>
</div>
And some jquery that sends a POST request with that file:
$("#upload-button").click(function() {
if ($('#doc-name').val() == '') {
var formData = new FormData();
var filename = $('#doc-name').val();
var uploaded = $('#doc-upload').val().split('\\');
var path = uploaded[uploaded.length - 1];
var file = $('#doc-upload').prop('files')[0];
formData.append("functionCall", "document-upload");
formData.append("filename", filename);
formData.append("path", path);
formData.append("file", file);
$.ajax({
url: '/assets/functions.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function(e) {
console.log(e);
},
error: function(jqXHR, textStatus, errorMessage) {
console.log(jqXHR);
console.log(textStatus);
console.log(errorMessage);
}
});
)};
This sends to my functions file, which is set up kind of odd (it might actually be standard practice, I've just never seen it like this) in that it's one big switch statement; which case gets run is dependent on the functionCall variable passed in. So here is the function code for that specific case statement:
.
.
.
case "doc-upload":
$filename = $_POST['filename'];
$path = $_POST['path'];
$file = $_FILES['file'];
$uploadQuery = "INSERT INTO uploads (filename, path) VALUES ('$filename', '$path')";
$upload = mysql_query($uploadQuery);
if (move_uploaded_file($_FILES['file']['tmp_name'], 'test/' . $_FILES['files']['name'])) {
echo 'yay';
} else {
echo 'such is life';
}
Everything above the move_uploaded_file line works great, but I keep getting the 'such is life' line returned, and the transferred file does not show up in 'test/'. I know both the test folder and uploaded file are present thanks to a file_exists check. Any ideas about what I might have done wrong?
Related
I have been working on a project, using Summernote. My project is like a blog system and I need to upload contents and images.
I have checked the other posts here and other places and managed to insert images to the file with ajax where I want to save the images. However, when I am editing, an image is there but once I click "update button" (submit button in a form), the images won't be there anymore.
I also check the inspect and resource says
Request URL: http://localhost/cms/admin/includes/images/42a0e188f5033bc65bf8d78622277c4e.JPG
This is the right path but after updating, I get a message like
Request URL: http://localhost/%22includes/images/42a0e188f5033bc65bf8d78622277c4e.JPG/%22
Also status code says
Status Code: 403 Forbidden
Here is my code
$('#summernote').summernote({
callbacks: {
onImageUpload: function(files) {
for(let i=0; i < files.length; i++) {
$.upload(files[i]);
}
}
},
height: 300,
});
$.upload = function (file) {
let out = new FormData();
out.append('file', file, file.name);
$.ajax({
method: 'POST',
url: './includes/editor-upload.php',
contentType: false,
cache: false,
processData: false,
data: out,
success: function(url) {
$('#summernote').summernote("insertImage", url, 'filename');
},
error: function (jqXHR, textStatus, errorThrown) {
console.error(textStatus + " " + errorThrown);
}
});
};
And this is my php code (editor-upload.php)
if ($_FILES['file']['name']) {
if (!$_FILES['file']['error']) {
$name = md5(rand(100, 200));
$ext = explode('.', $_FILES['file']['name']);
$filename = $name . '.' . $ext[1];
$destination = 'images/' . $filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo 'includes/images/' . $filename;//change this URL
}
else
{
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
Insert uploaded image to summernote editor
Summernote image upload
Summernote 0.8.12 Image Upload And Delete
I have tried these but nothing worked for me.
I have of course Summernote js and css file and am using Summernote 0.8.18
I am sure I am doing something wrong but I can't figure this out yet.
I am hoping somebody can help me out.
If the images folder is inside of the includes folder, change the following line:
$destination = 'images/' . $filename;
to
$destination = './includes/images/' . $filename;
Next, enter the full URL name and the full path to the image instead of
echo 'includes/images/' . $filename;
Also, the editor-upload.php file in your Ajax upload script may be causing the 403 errors. if the upload file is not in the same folder as your form and index.php page, it can prove problematic.
Try moving the file to the same folder as your form with the summer note editor, and enter the file in your Ajax script as
'editor-upload.php'
I just moved my local code over to live server. Everything is working but when I try to upload an image on the live server I get "Unprocessable Entity" error. The file upload works perfectly on my local server. I am using Windows server with IIS and PHP 7.2 and my project is using laravel 5.5
I have already tried given full control permissions to IUSER and IIS_IUSRS. I also tried updating the php.ini file (file_uploads = On, upload_max_filesize = 20M,post_max_size = 20M)
My Form
<form class='form-inline' id='edit-property-image' enctype='multipart/form-data'>
<input type='hidden' id='property' value='$id' name='property'>
<input type='file' class='custom-file-input' id='propertyImage' name='propertyImage' onchange='propertyImageChange(this)'>
<a href='javascript:updatePropertyImage($id)' class='btn btn-primary'>Update Image</a>
</form>
Ajax Method
function updatePropertyImage(id)
{
$.ajax({
data:new FormData($("#edit-property-image")[0]),
async:false,
type:'post',
processData: false,
contentType: false,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: 'POST', // Type of response and matches what we said in the route
url: '/property/updateImage', // This is the url we gave in the route
success: function(response){ // What to do if we succeed
if(response.response == "success") {
$('.modal').modal('hide');
propertyDetails(id);
}
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
alert(errorThrown);
}
});
}
Controller
$id = $request->input('property');
$this->validate($request,[
'propertyImage' => 'image|max:1999|required'
]);
$response = "failed";
//Handle File Upload
if($request->hasFile('propertyImage')){
//Get Filename with extension
$fileNameWithExt = $request->file('propertyImage')->getClientOriginalName();
// Get just filename
$filename = pathinfo($fileNameWithExt, PATHINFO_FILENAME);
//Get just extension
$extension = $request->file('propertyImage')->getClientOriginalExtension();
//Filename to store
$fileNameToStore = $id.'_'.time().'.'.$extension;
//Upload Image
$path = $request->file('propertyImage')->storeAs('public/property_images', $fileNameToStore);
$property = Property::find($id);
$property->image_url = $fileNameToStore;
$property->save();
$response = "success";
}
return response()->json([
'response' => $response,
]);
I fixed the issue. It was actually because my php.ini file did not specify a default temp folder. Once I added that the file upload worked.
I have tried majority of other questions here and other solutions and nothing has worked so far.
What I am trying to accomplish is upload images before Laravel's validation takes place, obviously I can't use the create function because it wont be hit until validation succeeds so I have made a custom function to do the file saving server side and trying to use Ajax to call that function every time a file is selected.
Current issue: doesn't seem like my Ajax is running on debugging its being skipped over,
second issue: I have a csrf token in my master template do i still need to add the ajax setup? if so is the way i am doing it correct.
Route:
Route::post('/upload', 'UploadController#uploadSubmit');
View:
<div>
<input type="file" id="fileupload" name="photos[]" data-url="/upload" multiple />
<br />
<div id="files_list"></div>
<p id="loading"></p>
<input type="hidden" name="file_ids" id="file_ids" value="" />
</div>
Ajax call:
$(document).ready(function(){
$("input").change(function(){
alert('triggered');
debugger;
$('#fileupload').fileupload({
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $(meta[name="csrf-token"]).attr('content')
}
dataType: 'json',
add: function (e, data) {
$('#loading').text('Uploading...');
data.submit();
},
done: function (e, data) {
$.each(data.result.files, function (index, file) {
$('<p/>').html(file.name + ' (' + file.size + ' KB)').appendTo($('#files_list'));
if ($('#file_ids').val() != '') {
$('#file_ids').val($('#file_ids').val() + ',');
}
$('#file_ids').val($('#file_ids').val() + file.fileID);
});
$('#loading').text('');
}
});
});
});
});
Controller:
public function uploadSubmit(Request $request){
$files = [];
dd(request());
foreach($learnerFiles as $key => $learnerFile){
if(count($learnerFile) > 0){
$path = $learnerFile->storeAs('public/uploads/learners', request('idNumber').'_'.$key.'.'.$learnerFile->extension());
$search = 'public/' ;
$trimmed = str_replace($search, '', $path) ;
//dd($learnerFiles);
$file = FileUpload::create([
'user_id' => $learner->id,
'file_name' => $key,
'path' => $trimmed
]);
}
else{
}
$file_object = new \stdClass();
$file_object->name = $key;
$file_object->size = round(Storage::size($path) / 1024, 2);
$file_object->fileID = $learner->id;
$files[] = $file_object;
}
return response()->json(array('files' => $photos), 200);
}
I'm using the following method to upload images using Ajax call and Laravel back-end.
var uploader = $('#image-uploader[type="file"]');
var data = new FormData();
$.each(uploader.files, function() {
data.append('image[]', this);
});
data.append('_token', $('[name="csrf-token"]').attr('content'));
var url = '/upload'; //Or any target path with post method
$.ajax({
url: url,
method: 'POST',
data: data,
processData: false,
contentType: false,
success: function(data) {
alert('succeed');
}
});
Consider you can access to image files in server-side using $_POST['image] array.
Hope this helps you.
I am curious to know that is it possible to show a docx file (which is available on server) inside a div without refreshing that page (using google doc viewer API or any other possible way).
Let me clear my requirement:-
HTML+JQUERY code:
<div class="browse-flie col-md-7">
<div class="alert alert-danger" style = "display:none;"></div>
<input type="file" id="uploaddocfile">
<button name="upload" value="Upload" class="btn EditBtn uplaod_file">Upload</button>
</div>
<div id = "myid" style = "height:500px;width:600px;"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$('.uplaod_file').on('click', function() {
var file_data = $('#uploaddocfile').prop('files')[0];
var ext = file_data.name.split('.').pop();
if(ext == 'docx'){
var form_data = new FormData();
form_data.append('file', file_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){
var response = $.parseJSON(php_script_response);
if(response.status == 'error'){
$('.alert-danger').css({'display':'block'});
$('.alert-danger').html('file upload failed please try again');
}
if(response.status == 'success'){
$('#myid').html("http://docs.google.com/gview?url=http://loalhost:8888/Grade/uploads/IEP Form-1.docx&embedded=true");
}
}
});
}else{
$('.alert-danger').css({'display':'block'});
$('.alert-danger').html('file extension must be docx'); return false;
}
});
</script>
PHP code:
<?php
// A list of permitted file extensions
$allowed = array('docx');
//echo "<pre/>";print_r($_FILES); die;
if(isset($_FILES['file']) && $_FILES['file']['error'] == 0){
$extension = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
if(!in_array(strtolower($extension), $allowed)){
echo '{"status":"error"}';
exit;
}
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/'.$_FILES['file']['name'])){
echo '{"status":"success"}';
exit;
}
}
echo '{"status":"error"}';
exit;
Now:
I have simple file upload code through jquery and php (working perfectly fine).
Now what I want is, after upload file when it comes success as a response then I want to show a doc file using API to my <div id = "myid" style = "height:500px;width:600px;"></div> (without refresh)
So what I tried:
$('#myid').html("http://docs.google.com/gview?url=http://loalhost:8888/Grade/uploads/IEP Form-1.docx&embedded=true");
(link changed for security reason but docx is available on server and I am able to open it directly)
But obviously it's not going to work.
So how can I do that?
Normally you'd do :
if(response.status == 'success'){
$('#myid').load("http://docs.google.com/gview?url=http://loalhost:8888/Grade/uploads/IEP Form-1.docx&embedded=true");
}
Instead of .html (which does something else).
However it's unlikely to work because the document you are accessing is not one that is managed by GoogleDocs (there may be cross-origin issues), so make sure you're allowing remote requests from Google to be made.
Instead you could try
if(response.status == 'success'){
$('#myid').html("<iframe src=\"http://docs.google.com/gview?url=http://loalhost:8888/Grade/uploads/IEP Form-1.docx&embedded=true\"></iframe>");
}
In case Google allows embedding of gview in iframes (though they may not).
Here i am doing upload the any file(there is no file size restriction and user can upload the any file extension) to server through my php code (in codigniter) but when I am trying to upload the file which is size 185MB so it is giving me error. I also add the php.ini to my folder structure on server which is got from my server support. I did increased the upload size and also increases another related attribute. I can upload the file which is size 20MB but did not able to upload the file size 50mb, 100mb, etc. upload maximum file size working on localhost but not working on server. Please below is the my code. Please help me any changes in my code
upload the files through ajax
$.ajax({
url: '<?php echo base_url();?>files>',
type: 'POST',
dataType :'json',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
if(myXhr.upload){
myXhr.upload.addEventListener('progress',progress, false);
}
return myXhr;
},
beforeSend:function() {
$("#progressbar").show();
$("#cmdSub").attr("disabled",true);
$("#cmdSub").val("Please Wait");
},
success: function (data) {
if(data.success != ""){
location.href = "<?php echo base_url();?>files/";
}
if(data.error != ""){
$("#f_name").val("");
$("#fnameinfo").html(data.error);
$("#cmdSub").attr("disabled",false);
$("#cmdSub").val("Submit");
}
},
error: function(xhr, textStatus, thrownError) {
alert("Error while uploading");
$("#cmdSub").attr("disabled",false);
$("#cmdSub").val("Submit");
$("#ffileinfo").html("");
},
data: formdata,
// this is the important stuf need to overide the usual post behavior
cache: false,
contentType: false,
processData: false
});
controller code
function uploadFile() {
$f_name = $_FILES['f_name']['name'];
$f_type = $_FILES['f_name']['type'];
$f_size = $_FILES['f_name']['size'];
$f_ext = pathinfo($_FILES['f_name']['name'], PATHINFO_EXTENSION);
$filename = pathinfo($_FILES['f_name']['name'], PATHINFO_FILENAME );
$filename = str_replace($arr_chars,"_",$filename);
$configFile = array (
'allowed_types' => '*',
'upload_path' => $file_upload_path,
'file_name' => $filename.'_'.$fid
);
$this->upload->initialize($configFile);
if($this->upload->do_upload('f_name')) {
//insert the record
} else {
$error = $this->upload->display_errors();
}
}
File upload size is probably a server config issue :)
Try this in your php.ini:
upload_max_filesize = 10M
post_max_size = 10M
--Edit (Thanks Big Chris)
The script could time out handling this request. So you should add this to your function
ini_set('max_execution_time', 120);
This tells php that this file can take up to 2 minutes to run
Hope that helps :)