Custom file name while keeping extension - laravel

Following this part of the docs:
https://laravel.com/docs/5.3/filesystem#file-uploads
I'm trying to store a file (an image) and specify a custom file name, but I don't want to change the extension.
If I do:
$request->file('avatar')->storeAs('avatars', 'custom_file_name');
The file will save as custom_file_name (with no extension), rather than custom_file_name.png).
How can I specify a custom file name while keeping the original file extension?

You can get extension of uploaded file with:
$extension = $request->photo->extension();
And apply it manually to the stored file name.
The UploadedFile class also contains methods for accessing the file's fully-qualified path and its extension. The extension method will attempt to guess the file's extension based on its contents.
https://laravel.com/docs/5.4/requests#files

The code below checks if request has a file by id/name avatar and then stores it with custom_name.{uploaded_files_extension}
if($request->hasFile('avatar')) {
$imgfile = Input::file('avatar');
$custom_name = 'custom_name'.$imgfile->getClientOriginalExtension();
$request->file('avatar')->storeAs('avatars', $custom_name);
}

Just to buttress #alexey-mezenin answer,
you might have issue adding the extension
//get extension
$extension = $request->file('featured_img')->extension();
$request->file('featured_img')->storeAs('/public/album',$post->title.'.'.$extension);
With that you can have a complete code stored in your /storage/public/album

Related

Download file contents and names into a List with Apache Camel FTP

I would like to download a list of files with name and content in Apache Camel.
Currently I am downloading the file content of all files as byte[] and storing them in a List. I then read the list using a ConsumerTemplate.
This works well. This is my Route:
from(downloadUri)
.aggregate(AggregationStrategies.flexible(byte[].class).accumulateInCollection(
LinkedList.class))
.constant(true)
.completionFromBatchConsumer()
.to("direct:" + this.destinationObjectId);
I get the List of all downloaded file contents as byte[] as desired.
I would like to extend it now so that it downloads the content and the file name of each file. It shall be stored in a pair object:
public class NameContentPair {
private String fileName;
private byte[] fileContent;
public NameContentPair(String fileName, byte[] fileContent) { ... }
}
These pair objects for each downloaded file shall in turn be stored in a List. How can I change or extend my Route to do this?
I tried Camel Converters, but was not able to build them properly into my Route. I always got the Route setup wrong.
I solved this by implementing a custom AggregationStrategy.
It reads the file name and the file content from each Exchange and puts them into a list as a NameContentPair objects. The file content and file name is present in the Exchange's body as a RemoteFile and is read from there.
The general aggregation implementation is based on the example implementation from https://camel.apache.org/components/3.15.x/eips/aggregate-eip.html
The aggregation strategy is then added to the route
from(downloadUri)
.aggregate(new FileContentWithFileNameInListAggregationStrategy())
.constant(true)
.completionFromBatchConsumer()
.to("direct:" + this.destinationObjectId);

Manually populate an ImageField

I have a models.ImageField which I sometimes populate with the corresponding forms.ImageField. Sometimes, instead of using a form, I want to update the image field with an ajax POST. I am passing both the image filename, and the image content (base64 encoded), so that in my api view I have everything I need. But I do not really know how to do this manually, since I have always relied in form processing, which automatically populates the models.ImageField.
How can I manually populate the models.ImageField having the filename and the file contents?
EDIT
I have reached the following status:
instance.image.save(file_name, File(StringIO(data)))
instance.save()
And this is updating the file reference, using the right value configured in upload_to in the ImageField.
But it is not saving the image. I would have imagined that the first .save call would:
Generate a file name in the configured storage
Save the file contents to the selected file, including handling of any kind of storage configured for this ImageField (local FS, Amazon S3, or whatever)
Update the reference to the file in the ImageField
And the second .save would actually save the updated instance to the database.
What am I doing wrong? How can I make sure that the new image content is actually written to disk, in the automatically generated file name?
EDIT2
I have a very unsatisfactory workaround, which is working but is very limited. This illustrates the problems that using the ImageField directly would solve:
# TODO: workaround because I do not yet know how to correctly populate the ImageField
# This is very limited because:
# - only uses local filesystem (no AWS S3, ...)
# - does not provide the advance splitting provided by upload_to
local_file = os.path.join(settings.MEDIA_ROOT, file_name)
with open(local_file, 'wb') as f:
f.write(data)
instance.image = file_name
instance.save()
EDIT3
So, after some more playing around I have discovered that my first implementation is doing the right thing, but silently failing if the passed data has the wrong format (I was mistakingly passing the base64 instead of the decoded data). I'll post this as a solution
Just save the file and the instance:
instance.image.save(file_name, File(StringIO(data)))
instance.save()
No idea where the docs for this usecase are.
You can use InMemoryUploadedFile directly to save data:
file = cStringIO.StringIO(base64.b64decode(request.POST['file']))
image = InMemoryUploadedFile(file,
field_name='file',
name=request.POST['name'],
content_type="image/jpeg",
size=sys.getsizeof(file),
charset=None)
instance.image = image
instance.save()

System.IO.File.Exists() returns false

I have a page where I need to display an image which is stored on the server. To find that image, I use the following code:
if (System.IO.File.Exists(Server.MapPath(filepath)))
When I use this, I get a proper result as the file is present.
But when I give an absolute path like below:
if (System.IO.File.Exists("http://myserever.address/filepath"))
It returns false.
The file is physically present there, but I don't know why it's not found.
The path parameter for the System.IO.File.Exists is the path to an actual file in the file system.
The call to Server.MapPath() changes the URI into an actual file path.
So it is working as intended.
You can't use HTTP paths in File.Exists. It supports network shares and local file systems. If you want to do this in a web application on the server side. First use Server.MapPath() first to find the physical location and then use File.Exists.
Read about Server.MapPath here: http://msdn.microsoft.com/en-us/library/ms524632%28v=vs.90%29.aspx
Eg.
string filePath = ResolveUrl("~/filepath/something.jpg");
if (File.Exists(Server.MapPath(filePath)))
{
//Do something.
}

How do you customize the identifier used by MinispadeFilter in rake-pipeline

Per this question: Setting up rake-pipeline for use with handlebars alongside Google App Engine
I'm using a MinispadeFilter as my dependency management system via rake-pipeline.
The weird thing I'm seeing is the coffeescript and handlebars files have their minispade identifier set to a tmp directory (I'm assuming, where the work is being done). screencast.com/t/wIXmREcreW
Is there a way to set that to a root path such that it is normalized? Likewise my js files, while not pointing to a tmp path, are pointing to the original assets path instead of the public path. I know its just an identifier, but should I expect them to reference the public path? screencast.com/t/k9kZNcPo
The MinispadeFilter is pretty dumb about generating module identifiers by default. It just names them after the path of the input files. You're seeing the tmp dirs in there from handlebars and coffeescript because the minispade filter is getting the module id from the place where the pipeline turns them into javascript.
The filter takes a :module_id_generator option which allows you to customize the generation of module ids. If you're not familiar with Ruby, this may be a little heavy for you, so bear with me. The module_id_generator option takes a Ruby proc, which is like an anonymous function in JS. The filter then takes this proc that you pass in and executes it for each input file, passing your proc a FileWrapper object representing the input file, and your proc should return a string that will be used as the module id for that file.
Here's a match block from one of my projects:
match "**/*.js" do
minispade :module_id_generator => proc { |input| input.path.sub(/lib\//, 'timelog/').sub(/\.js$/, '') }
concat "js/app.js"
end
The :module_id_generator is a proc which takes a FileWrapper named input and turns it into the module id I want. The input file's path is available as the path method on input. In this case, my JS files are in a lib/ directory, so I use Ruby's sub method to replace the beginning lib/ part of the path with timelog (the name of the project) then again to remove the .js extension. So a js file named lib/models.js would get a module id of timelog/models.

How to create the path to desktop for the target user..in C#.net

I am developing image extraction application in .net using C# in VS2010.
i have created a path ,where the image will be extracted.But this path is specific to my system.
string image1 = "c:\\Users\\Raghu\\Desktop\\r.bmp";
I want a path which should be general i.e when the project will be deployed ,the output file should be extracted in Target Users desktop.
how create a folder on desktop and and all my extracted files goes in it.
Any ideas! please help me!!
Next code will return path to the desktop of current user:
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
So, in your case it would be
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
string image1 = System.IO.Path.Combine(desktop, "r.bmp");
Environment.SpecialFolder (http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx) contains many definitions of system folder paths. Take a look which you need.
You would use the DesktopDirectory for Environment.SpecialFolder. Something like this:
public static string GetDesktopDirectory()
{
return Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
}
Then using the result of that method, you can use Path.Combine to append a file name to it.
var myFilePath = Path.Combine(GetDesktopDirectory(), "r.bmp");
Path.Combine is the general solution for this, as directly concating strings may result in double slashes, etc. This takes care of that for you.

Resources