For some reason I am not able to delete a file I upload with $request->file->store.
I tried \File::delete, \File::Delete, \Storage::Delete, and \Storage::delete. I want to avoid using unlink as that is not the laravel way.
May you please help me?
This is my code:
if ($user->avatar_path) {
// delete old one
\File::delete(app_path().$avatar_path);
}
$avatar_path = $request->file('avatar')->store('uploads/users/'.$user->id.'/avatar', 'public');
$user->update($request->except('avatar') + ['avatar_path' => $avatar_path]);
We see here that I check if there is an old avatar, and then I want to delete it. Then I upload the next one and update the database with the new path.
Finally solved this. I had to use Storage::disk('public')->delete($old_avatar_path);. Final code:
if ($request->has('avatar')) {
$old_avatar_path = $user->avatar_path;
$avatar_path = $request->file('avatar')->store('avatars', 'public');
$user->update($request->except('avatar') + ['avatar_path' => $avatar_path]);
if ($old_avatar_path) {
// delete old one
Storage::disk('public')->delete($old_avatar_path);
}
Related
I'm trying to save some data from API in a .json file using cy.writeFile method, but my code is replacing the existing data.
What I need is to add additional data.
cy.intercept('POST', 'http://viasphere.localhost/sites/datatable').as('response')
cy.contains('Sortir').click()
cy.wait('#response').get('#response').then(xhr => {
console.log(xhr)
let siteID = xhr.response.body.data[0].id
let creationDate = xhr.response.body.data[0].created_at
let RM = xhr.response.body.data[0].metal_rollout
let clientGroup = xhr.response.body.data[0].client_contact_group
cy.writeFile('SiteAPIdata.json', {siteID2: siteID})
After the run, the data existing inside the SiteAPIdata.json file is being replaced by the new data.
The SiteAPIdata.json file is located in cypress/fixtures/ folder.
Thank you!
Assuming you want to append the new data to the existing data, that can easily be accomplished by using cy.readFile() before writing.
...
cy.readFile('SiteAPIdata.json').then((data) => {
data.siteID = siteID;
cy.writeFile('SiteAPIdata.json', data);
})
I am doing CRUD operations for images. when I am doing the update operation image gets updated but the old image doesn't delete. The following code updates only the file name in the database but I need to remove the old image from the destination folder too while updating else the folder size will become too large. Any ideas would be great. Here my code.
<input type="file" name="profileimage" value="{{ isset($editabout) ? $editabout->profileimage : '' }}" class="custom-file-input" id="exampleInputFile">
Here is my controller
public function update(updateAboutusProfile $request, AboutUs $about)
{
$data=$request->only(['profiletext']);
if($request->hasFile('profileimage')){
$profileimage = $request->profileimage->store('aboutus', 'public');
$oldimage = $about->profileimage;
Storage::delete($oldimage);
$data['profileimage'] = $profileimage;
}
$about->update($data);
toastr()->success('Profile updated successfully');
return redirect(route('about.index'));
//
}
What can be the error I need to resolve,
thank you
Try setting the disk you used to store the file
Storage::disk('public')->delete($oldimage);
Delete image from your server, you have to reference location of file in directory server, means you could not reference by url link to delete it.
Laravel file is locate in public folder.
Example: your files are located in public/images
$image_path = "/images/filename.ext"; // Value is not URL but directory file path
if(File::exists($image_path)) {
File::delete($image_path);
}
Enjoy ;)
You should save the path of the file to the database and then simply remove it using \Storage::delete() facade.
Store image using hash name
if($request->hasFile('profileimage')){
$store_path = 'aboutus';
$profileimage = $request->profileimage->store($store_path,'public');
$oldimage = $about->profileimage;
$file_address = $store_path.'/'.$request->profileimage->hashName();
\Storage::disk('public')->delete($oldimage);
$data['profileimage'] = $file_address;
}
Store image using original name
if($request->hasFile('profileimage')){
$store_path = 'aboutus';
$profileimage = $request->profileimage->storeAs($store_path, $uploadedFile->getClientOriginalName(),'public');
$oldimage = $about->profileimage;
$file_address = $store_path.'/'.$request->profileimage->getClientOriginalName();
\Storage::disk('public')->delete($oldimage);
$data['profileimage'] = $file_address;
}
Delete the old image while updating
public function update(Request $request, $id)
{
// other updates
if ($request->hasFile('image')) {
//delete old image if exist
if (File::exists(public_path($oldImage))) {
File::delete(public_path(oldImage));
}
//new image process
}
}
I want to copy storage.db to documents or downloads folder. It's very easy to get the file path:
const filePath = application.android.context.getDatabasePath("storage.db").getAbsolutePath();
But, what isn't that easy is to copy that file to a folder users have access to. I searched this whole forum, and I found nothing useful for my case.
I'm using NativeScript 4.0.1 with vanilla JS.
If you want to share the DB file, the easiest way is to use nativescript-share-file plugin, send the file path and it will give you a nice dialog with intent picker, user may choose to Email the file Or save it to local folder etc.,
const shareFile = new ShareFile();
shareFile.open({
path: filePath,
});
I finally found the solution. I've seen so many users trying to achieve this, and I hope this will help all of you.
Add this to your AndroidManifest.xml:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Install nativescript-permissions:
npm i nativescript-permissions
Asking for permission:
const permissions = require('nativescript-permissions');
permissions.requestPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE, "");
Require the necessary modules:
const fileSystemModule = require("tns-core-modules/file-system");
const application = require("application");
Then, create this function where you need to use it:
function copyFile() {
var myInput = new java.io.FileInputStream(appModule.android.context.getDatabasePath("storage.db").getAbsolutePath());
var myOutput = new java.io.FileOutputStream("/storage/emulated/0/databases/storage.db");
try {
var buffer = java.lang.reflect.Array.newInstance(java.lang.Byte.class.getField("TYPE").get(null), 1024);
var length;
while ((length = myInput.read(buffer)) > 0) {
myOutput.write(buffer, 0, length);
}
}
catch (err) {
console.info("Error", err);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
exports.copyFile = copyFile;
In my case, the file storage.db will be copied to /storage/emulated/0/databases. If you need to create a folder, just do the following:
try {
var javaFile = new java.io.File("/storage/emulated/0/newfolder");
if (!javaFile.exists()) {
javaFile.mkdirs();
javaFile.setReadable(true);
javaFile.setWritable(true);
}
}
catch (err) {
console.info("Error", err);
}
If the destination folder has a file with the same name as the one you want to copy, you need to remove it first. That's why you should create a specific folder to guarantee it's empty.
Is there a way to zip and download files and folders which are in Amazon S3 bucket, together in Laravel? I Want to zip the three folders and one file in the picture together and download it
Here's a half baked solution in a route file. Hope it helps.
https://flysystem.thephpleague.com/docs/adapter/zip-archive/
composer require league/flysystem-ziparchive
I put this in routes/web.php just to play with.
<?php
use Illuminate\Support\Facades\Storage;
use League\Flysystem\Filesystem;
use League\Flysystem\ZipArchive\ZipArchiveAdapter;
Route::get('zip', function(){
// see laravel's config/filesystem.php for the source disk
$source_disk = 's3';
$source_path = '';
$file_names = Storage::disk($source_disk)->files($source_path);
$zip = new Filesystem(new ZipArchiveAdapter(public_path('archive.zip')));
foreach($file_names as $file_name){
$file_content = Storage::disk($source_disk)->get($file_name);
$zip->put($file_name, $file_content);
}
$zip->getAdapter()->getArchive()->close();
return redirect('archive.zip');
});
You'll definitely want to do something different than just plopping it in the public dir. Maybe stream it out straight out as a download or save it somewhere better. Feel free to post comment/questions and we can discuss.
I did it the following way after looking at some solutions by streaming the zip directly to the client by using https://github.com/maennchen/ZipStream-PHP :
if ($uploads) {
return response()->streamDownload(function() use ($uploads) {
$opt = new ArchiveOptions();
$opt->setContentType('application/octet-stream');
$zip = new ZipStream("uploads.zip", $opt);
foreach ($uploads as $upload) {
try {
$file = Storage::readStream($upload->path);
$zip->addFileFromStream($upload->filename, $file);
}
catch (Exception $e) {
\Log::error("unable to read the file at storage path: $upload->path and output to zip stream. Exception is " . $e->getMessage());
}
}
$zip->finish();
}, 'uploads.zip');
}
I want to load datafixtures with DoctrineFixturesBundle with images but I don't know how to make it work.
I tried this one :
public function load(ObjectManager $manager)
{
$imageGrabTail = new Image();
$imageGrabTail->setTrick($this->getReference('grab-tail'));
$imageGrabTail->setUpdatedAt(new \DateTimeImmutable());
$file = new UploadedFile($imageGrabTail->getUploadDir() . '/63.jpeg', 'Image1', null, null, null);
$imageGrabTail->setFile($file);
$manager->persist($imageGrabTail);
$manager->flush();
}
My method getUploadDir():
public function getUploadDir()
{
return 'uploads/img';
}
But I have an error :
[Symfony\Component\HttpFoundation\File\Exception\FileNotFoundException]
The file "uploads/img/63.jpeg" does not exist
My file 63.jpeg exists on this folder.
Is there someone who can explain to me why it's not working ?
Thanks !
This object UploadedFile is for file that are upload through a request. Here there is no request, so you have to use get_file_contents() function in order to access your data.
Try this function and tell us the result of it.
To solve it I've just followed this thread
How would you add a file upload to a Symfony2 DataFixture?