I'm trying to upload a file using laravel and vue. When i console.log() the file, I get the picture below but in the controller, I'm receiving a tmp path only.
Vue
onFileChange(e) {
ths.file = e.target.files[0];
console.log(this.file)
},
submit(){
let form= new FormData()
form.append('file', this.file)
axios.post('/api/archieve',form).then(res=>{
//
})
},
Controller
return $request->file //returns "C:\xampp\tmp\php5E67.tmp"
UPDATE
I've checked using dd($request->file('file')); and it returns the below image but the realPath is wrong. The image is stored in a different folder on my pc.
Please try add header.
onFileChange(e) {
this.file = e.target.files[0];
console.log(this.file)
},
submit() {
let form= new FormData()
form.append('file', this.file)
axios.post('/api/archieve', form, {
headers: { 'Content-Type': 'multipart/form-data' }
}).then(res=>{
//
})
},
and in you controller, check
$request->file('file');
To store file
use Illuminate\Support\Facades\Storage;
....
$file = $request->file('file');
$path = 'my-uploads'; // path or folder where to save it
$storePath = Storage::put($path, $file);
$fileName = basename($storePath); // generated file name
$filePath = $path . '/' . $fileName; // path of file in your storage
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 am working on a Laravel 8 application that requires user registration and login.
Alter registration, the users have the possibility to replace the default avatar image with a picture of their choice. They are also able to revert to the default avatar (default.png).
A problem arises while trying to remove the image file itself from the server after delete.
In routes\web.php I have:
Route::post('/dashboard/profile/deleteavatar/{id}/{fileName}', [App\Http\Controllers\Dashboard\UserProfileController::class, 'deleteavatar'])->name('profile.deleteavatar');
In Http\Controllers\Dashboard\UserProfileController.php I have:
// Delete avatar
public function deleteavatar($id, $fileName) {
$current_user = Auth::user();
$current_user->avatar = "default.png";
$current_user->save();
if(File::exists(public_path('images/avatars' . $fileName))){
File::delete(public_path('images/avatars' . $fileName));
}
}
In app.js:
(function() {
//Delete Avatar
$('#delete-avatar').on('click', function(evt) {
evt.preventDefault();
var $avatar = $('#avatar-container').find('img');
var $topAvatar = $('#top_avatar');
var $trashIcon = $(this);
var defaultAvatar = APP_URL + '/images/avatars/default.png';
//Get user's ID
var id = $(this).data('uid');
var fileName = $avatar.attr('src').split('/').reverse()[0];
if (confirm('Delete the avatar?')) {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
$.ajax({
url: APP_URL + `/dashboard/profile/deleteavatar/${id}/${fileName}`,
method: 'POST',
data: {
id: id,
fileName: fileName,
_token: CSRF_TOKEN,
},
success: function() {
$avatar.attr('src', defaultAvatar);
$topAvatar.attr('src', defaultAvatar);
$trashIcon.remove();
}
});
}
});
})();
When I delete the user's avatar, the following happens:
The avatar is replaced with default.png in the avatar column of the users table.
The Chrome console shows a 500 (Internal Server Error) error.
The image is NOT removed from the dearver.
What am I missing?
If you images in public folder then you have imported wrong File import
You should import
use Illuminate\Support\Facades\File;
then i assume images are in public/images/avatars/avatar.png.
if(File::exists(public_path('images/avatars/' . $fileName))){
File::delete(public_path('images/avatars/' . $fileName));
}
Suppose if you have files storage/app/public/images/avatars then you should do the following
if (Storage::exists('public/images/avatars/'. $fileName)) {
Storage::delete('public/images/avatars/'. $fileName);
}
Also don't forget to import right one
use Illuminate\Support\Facades\Storage;
This method is dangerous but should be work:
In Http\Controllers\Dashboard\UserProfileController.php you can use #unlink for delete file an ignore errors, if your file exists will be deleted, and if not nothing occurs.
// Delete avatar
public function deleteavatar($id, $fileName) {
$current_user = Auth::user();
$current_user->avatar = "default.png";
$current_user->save();
#unlink(public_path('images/avatars/' . $fileName));
}
I am trying to set up a media asset database using Laravel, Vue, Axios and Intervention image.
I want the user to be able to set a desired image height and width before downloading an image. This is then sent to the controller using an axios post-request. Inside the controller, intervention image is working its magic(k) and returning my resized file as a response.
Now I want the image that's being returned as a response to trigger a download. What do I need to do with my axios-response?
Here's what I currently have:
Axios-Request:
resize(file) {
this.file = file;
let formData = new FormData();
formData.append('imageHeight', this.imageHeight);
formData.append('imageWidth', this.imageWidth);
axios.post('files/resize/' + file.id, formData).then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error);
this.errors = error.response.data.errors;
this.showNotification(error.response.data.message, false);
this.fetchFile(this.activeTab, this.pagination.current_page);
});
}
Controller:
public function resize($id, Request $request)
{
$file = File::where('id', $id)->where('user_id', Auth::id())->first();
$originalImage = $file->getName($file->type, $file->name, $file->extension);
$originalImagePath = Storage::get($originalImage);
$imageHeight = $request['imageHeight'];
$imageWidth = $request['imageWidth'];
if ($img = Image::make($originalImagePath)) {
return $img->resize($imageWidth,$imageHeight)->response();
}
}
You'll want the Content-Disposition response header to be attachment rather than inline.
http://image.intervention.io/use/http
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'm trying to download a file using force_download in codeigniter.
I create an AJAX call like this
$.ajax({
type: 'POST'
, url: '<?php echo base_url('downloadPayroll'); ?>'
, data: { filename: filename }
});
And here is my controller
public function downloadPayroll() {
$filename = $this->input->post('filename');
$fileContents = file_get_contents(base_url('assets/uploads/'. $filename));
force_download($filePath, $fileContents);
}
I know I have the correct path and filename but it doesn't download anything.
What am I doing wrong because the documentation for Download Helper is very limited.
Just a note to anyone else who may be having this problem: Make sure you have a file extension on the filename you supply for the first argument to force_download().
CodeIgniter uses this to set the MIME type, and it doesn't seem to work without.
for more CodeIgniter - force_download() problem.
$name = 'myfile.txt';//file extension is required
force_download($name, NULL);//if you dont want to send data set NULL
And Don't forget to load download helper first.
$this->load->helper('download');
Please try using below code. You are passing wrong variable name for force_download
$filename = $this->input->post('filename');
$fileContents = file_get_contents(base_url('assets/uploads/'. $filename));
$file='test.pdf';
force_download($file, $fileContents);
there is no way to download a file via an ajax request like that - try this instead
your JS File
$.ajax({
type: 'POST'
, url: '<?php echo base_url('downloadPayroll'); ?>'
, data: { filename: filename },
success: function(strUrl)
{
var link = document.createElement('a');
link.style = "display: none";
link.href = strUrl;
document.body.appendChild(link);
link.click();
setTimeout(function () {
document.body.removeChild(link);
}, 5000);
}
});
Your Controller:
public function downloadPayroll()
{
$filename = $this->input->post('filename');
echo base_url('assets/uploads/'. $filename);
}
you are missing the helper
public function downloadPayroll() {
$filename = $this->input->post('filename');
$fileContents = file_get_contents(base_url('assets/uploads/'. $filename));
$this->load->helper( 'download' );
force_download($filePath, $fileContents);
}