I'm using laravel 5.8 and intervention image to upload and resize an image.
I want to store this in storage/app/public/images folder and I'm trying to use the storage facade to auto generate a unique name but the following doesn't work:
$file = $request->file('file');
$image = Image::make($file->getRealPath())->resize(360, 180);
Storage::disk('public')->putFile('images', $image->getEncoded());
Is it possible to auto generate unique file name using the storage facade for images similar to the when you upload normal files as follows:
Storage::disk('local')->putFile('forms', $request->file('file'));
Uploaded files use temporary file names when uploaded in your application. These can serve as unique names you can use to save.
You can access this using the ->getPathName() method of the uploaded file.
Alternatively, you can use ->getClientOriginalName() for the original name of the file.
With Intervention/Image, you can use the ->save() method to save this image to the destination folder:
$file = $request->file('file');
$image = Image::make($file->getRealPath())
->resize(360, 180)
->save(storage_path('app/public/images/'.$file->getPathName());
I haven't tested this but I hope this helps.
$image = Image::make($request->file('file'))->resize(360, 180)
->save(storage_path('app/public/images/'.$file->getPathName());
Related
How can I convert the TYPO3 file uri t3://file?uid=54 to be usable for other TYPO3 methods which need a file identifier?
The file uri is returned by a flexform which selects a XML file. This XML file should be read.
However I cannot find a useful API function in the TYPO3 Core.
$paramTestFile = 't3://file?uid=54';
$xmlString = GeneralUtility::getURL($paramTestFile);
The above code fails for TYPO3 URIs.
The file reference with uid=54 is at "fileadmin/example.xml".
The Filelist backend module shows the details of this file.
However I need this file path also in the PHP code in order to read in the file.
use TYPO3\CMS\Core\LinkHandling\FileLinkHandler;
$fileHandler = GeneralUtility::makeInstance(FileLinkHandler::class);
$fileInfo = $fileHandler->asString($paramTestFile);
It is not possible to use $paramTestFile in the above example.
The class FileLinkHandler and its method asString does exactly the opposite of what I need.
$content = #file_get_contents($url);
However the absolute file path is needed for the read method . How can I convert the FAL file URI into the file identifier?
use TYPO3\CMS\Core\Resource\StorageRepository;
$storageRepository = GeneralUtility::makeInstance(StorageRepository::class);
$defaultStorage = $storageRepository->getDefaultStorage();
$fileInfo = $defaultStorage->getFileByIdentifier($paramTestFileIdentifier);
To resolve a t3://file... URN use TYPO3\CMS\Core\LinkHandling\LinkService::resolve(). This method will return an array with a key file containing a TYPO3\CMS\Core\Resource\FileInterface. This also works for other URNs but will return another array structure.
Then use the getContents() method of the FileInterface to finally get the content of the file.
The documentation is not very detailed for this part of the core so I have linked you directly to the related sources.
I would like to save variables as mat files on s3. The example on the official site shows "tall table" only. Maybe I can use the "system" command overstep MATLAB but I am looking for a straight forward solution.
Any suggestion?
It does look like save does not support saving to remote filesystems.
You can, however, write matrices, cells, tables and timetables.
An example which uses writetable:
LastName = {'Smith';'Johnson';'Williams';'Jones';'Brown'};
Age = [38;43;38;40;49];
T = table(Age,LastName)
writetable(T,'s3://.../table.txt')
Note:
To write to a remote location, filename must contain the full path of
the file specified as a uniform resource locator (URL) of the form:
scheme_name://path_to_file/my_file.ext
To obtain the right URL of the bucket, you can navigate to the contents of the s3 bucket, select a file in there, choose Copy path and remove the name of the file (e.g table.txt).
The alternative is, as you mentioned, a system call:
a = rand(5);
save('matExample','a');
system('aws s3api put-object --bucket mybucket --key=s3mat.mat --body=matExample.mat')
the mat file matExample.mat is saved as s3.mat on the server.
So in google-cloud-storage if you upload more than one file with the same name to it the last will overwrite what was uploaded before it.
If I want to upload more than one file with the same name I should append some unique thing to the file name e.g. timestamp, random UUID.
But by doing so I'll lose the original file name while downloading, because I want to serve the file directly from google.
If we used the unique identifier as a folder instead of appending it to the file name, e.g. UUID +"/"+ fileName then we can download the file with its original name.
You could turn on Object Versioning which will keep the old versions of the object around.
Alternatively, you can set the Content Disposition header when uploading the object, which should preserve whatever filename you want on download.
instead of using object versioning, you can attach the UUID (or any other unique identifier) and then update the metadata of the object (specifically the content disposition), the following is a part of a python script i've used to remove the forward slashes - added by google cloud buckets when to represent directories - from multiple objects, it's based on this blog post, please keep in mind the double quotes around the content position "file name"
def update_blob_download_name(bucket_name):
""" update the download name of blobs and remove
the path.
:returns: None
:rtype: None
"""
# Storage client, not added to the code for brevity
client = initialize_google_storage_client()
bucket = client.bucket(bucket_name)
for blob in bucket.list_blobs():
if "/" in blob.name:
remove_path = blob.name[blob.name.rfind("/") + 1:] # rfind gives that last occurence of the char
ext = pathlib.Path(remove_path).suffix
remove_id = remove_path[:remove_path.rfind("_id_")]
new_name = remove_id + ext
blob.content_disposition = f'attachment; filename="{new_name}"'
blob.patch()
I have form with fields like
'name, firstname, street, zip, city and image'.
The image was an upload
field. Everything works fine, i can upload the image as Filereferrence. But the image was uploaded every time into "fileadmin/". I want to upload the image into "/uploads/<extensionname>" or "fileadmin/user_uploads/<extensionname>".
The part where the upload and file moving was realized look like.
$storageRepository = $this->objectManager->get('TYPO3\\CMS\\Core\\Resource\\StorageRepository');
$storage = $storageRepository->findByUid('1');
$fileData = array();
$fileData['name'] = $_FILES['tx_oaevents_eventslisting']['name']['image'][0];
$fileData['type'] = $_FILES['tx_oaevents_eventslisting']['type']['image'][0];
$fileData['tmp_name'] = $_FILES['tx_oaevents_eventslisting']['tmp_name']['image'][0];
$fileData['size'] = $_FILES['tx_oaevents_eventslisting']['size']['image'][0];
$newFileObject = $storage->addFile(
$fileData['tmp_name'], $storage->getRootLevelFolder(), $fileData['name']
);
This line deines the storage folder form database:
$storage = $storageRepository->findByUid('1');
which is fileadmin as default. But what is the best way to change/modify this storage folder destination?
If you want to specify the destination folder for your upload, I suggest you take a look at the FAL File Upload example from Helmut Hummel. For his example, there is also a blogpost which describes how the file upload works and why you should use a TypeConverter for FAL file upload in TYPO3 6.2+
I have implemented the solution several times and it works just great, since it covers a lot of scenarios you may run into when implementing a file upload (e.g. validation, error handling, file replacement if file exists)
I have a project with a image stored as a logo that I wish to use.
URL logoPath = new MainApplication().getClass().getClassLoader().getResource("img/logo.jpg");
Using that method I get the URL for the file and convert it to string. I then have to substring that by 5 to get rid of this output "file:/C:/Users/Stephen/git/ILLA/PoC/bin/img/logo.jpg"
However when I export this as a jar and run it I run into trouble. The URL now reads /ILLA.jar!/ and my image is just blank. I have a gut feeling that it's tripping me up so how do I fix this?
Cheers
You are almost there.
Images in a jar are treated as resources. You need to refer to them using the classpath
Just use getClass().getResource: something like:
getClass().getResource("/images/logo.jpg"));
where "images" is a package inside the jar file, with the path as above
see the leading / in the call - this will help accessing the path correctly (using absolute instead of relative). Just make sure the path is correct
Also see:
How to includes all images in jar file using eclipse
See here: Create a file object from a resource path to an image in a jar file
String imgName = "/resources/images/image.jpg";
InputStream in = getClass().getResourceAsStream(imgName);
ImageIcon img = new ImageIcon(ImageIO.read(in));
Note it looks like you need to use a stream for a resource inside an archive.