Laravel 7 change where file uploads to - file-upload

I have a file upload form in on of my blade files.
However when I upload the file I see its saving the file to /storage//Applications/MAMP/tmp/php/phpIVfP2L.mp4 how do I set this upload to be saved to a specific location like I want them saved in the Laravel public folder that is in the Laravel root directory so the path would be /public/trainingvideos
Below is my controller code where my file upload code is
public function addtraining(Request $req) {
//Save to a mysql database
//print_r($req->input());
$pwdata = new AddTraining;
$pwdata->userid = $req->userid;
$pwdata->video_title = $req->trainingtitle;
$pwdata->video_description = $req->trainingdesc;
$pwdata->video_url = $req->trainingvideo;
if($req->hasFile('trainingvideo')) {
// Let's do everything here
if($req->file('trainingvideo')->isValid()) {
//
$validated = $req->validate([
'trainingvideo' => 'mimes:mp4,mov|max:10000',
]);
$extension = $req->trainingvideo->extension();
$req->trainingvideo->storeAs('public_path()/public/trainingvideos', $req->trainingvideo.".".$extension);
$url = Storage::url($req->trainingvideo.".".$extension);
$pwdata->video_url = $url;
//Session::flash('success', "Success!");
}
}
//abort(500, 'Could not upload video :(');
$pwdata->save();

The /tmp directory is where files are temporarily stored when uploaded.
In your controller you need to go about actually storing that file, the docs cover this in depth; https://laravel.com/docs/7.x/requests#storing-uploaded-files
It's worth mentioning that if you leave the files in your tmp directory, they will be garbage collected at some point and so this is not a safe location to store files.

Related

using S3 Laravel8 create a unique folder with every upload file

I have this code is working perfectly fine, But I want when I upload the image 1st time to create a new folder and store the image, as I want 2nd time when I upload a new file to create a new unique folder and store the file...
Please help me with this if someone knows how to do this because I am new to Laravel.
public function storemultipleImages(Request $request)
{
$this->validate($request, ['image' => 'required|image']);
if ($request->hasfile('image')) {
$file = $request->file('image');
$name = time() . $file->getClientOriginalName();
$filePath = 'poster_art_1/' . $name;
Storage::disk('s3')->put($filePath, file_get_contents($file));
return back()->with('success', 'Image Uploaded successfully');
}
}

Fileinput issue in ActiveForm when updating via Yii 2

I am using Yii2 framwork. My file upload function worked well when I upload a single img, while when I click the posed article and I only want to update the post again(Suppose I didn't want to update the img, I only want to update other contents). But I found my uploaded file were replaced with an empty value(varchar type) when I click view. my uploaded img can't show out.
I do tried to fixed by myself as below, But the existing file value can't be saved when I click the submit button.
<?php
if (($post->file) != "") {
echo $form->field($post, 'file')->textInput()->hint('My currently uploaded file')->label('My Photo') ;
}
else{
echo $form->field($post, 'file')->fileInput()->hint('To upload a new file')->label('My Photo') ;
}
?>
When I click submit button, my existing file was gone.
Is there any good way to fix it.
Thanks for your opinions in advance.
Use another variable in your model for upload a file.
For example use file_field name for get file from submitted and store in file field.
class PostModel extends Model
{
/**
*
* #var UploadedFile
*/
public $file_field;
public function rules() {
return [
['file_field', 'file'],
];
}
}
echo $form->field($post, 'file_field')->fileInput()->hint('To upload a new file')->label('My Photo') ;
$post->file_field = UploadedFile::getInstance($post, 'file_field');
For upload new file check the file_field:
if ($post->file_field) {
// $post->file old file
// Save $post->file_field and store name in $post->file
}
Add a rule to your model rules:
[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
and check for an empty upload in your controller:
if (Yii::$app->request->isPost) {
$ok = true;
// process your other fields...
...
// process image file only if there is one
$post->file= UploadedFile::getInstance($post, 'file');
if ($post->file && $post->upload()) {
}
if ($ok) {
return $this->redirect(...);
}
}
See Yii2 docs and the Yii2 guide for detailed infos about file upload.

Laravel 5 issues uploading/saving pdf

I'm using Laravel 5.6, jQuery 3.3.1, bootstrap 3.3.7, and PHP 7.1.4
I need to be able to allow users to upload files and pictures, basically jpg, gif, png, and pdf. I am using the public disk and storing the files in storage/app/public/folder_name where folder_name is defined in an env file
FILESYSTEM_DRIVER=public
PO_FILE_FOLDER=purchase_orders
INSURANCE_FILE_FOLDER=insurance
NOTE_FILE_FOLDER=notes
RENTAL_AGREEMENT_FILE_FOLDER=rental_agreements
SIGNATURES=signatures
They are then defined in config/app
'insurance_file_folder' => env('INSURANCE_FILE_FOLDER', ''),
'po_file_folder' => env('PO_FILE_FOLDER', ''),
'note_file_folder' => env('NOTE_FILE_FOLDER', ''),
'rental_agreement_file_folder' => env('RENTAL_AGREEMENT_FILE_FOLDER', ''),
'max_image_width' => env('MAX_IMAGE_WIDTH', 500),
'filesystem_driver' => env('FILESYSTEM_DRIVER', 'local'),
When I upload image files they upload to the appropriate folder but when I try to upload pdf files the system creates a new folder named as what I'm naming the file and the pdf is in the new folder with a random name. I'm using the exact same code to upload both images and pdf files so I can't figure out why it works for one but not the other.
Here is my controller code
public function store(PurchaseOrderRequest $poRequest, Customer $customer)
{
$purchaseOrder = $customer->purchaseOrders()->create($poRequest->except('attachment'));
if ($poRequest->hasFile('attachment')) {
$purchaseOrder->saveFile(config('app.po_file_folder', ''), $poRequest->file('attachment'));
}
return redirect()->action('CustomerController#edit', $customer)->with('alert', 'Purchase Order created.');
}
My model PurchaseOrder saveFile code
public function saveFile($folder_name, $file)
{
// if file submited then check if file already exists, if so delete file and create new file
$file_name = $this->createFileName();
File::removeFiles($folder_name.'/'.$file_name, FALSE);
$file_name = $file_name.'.'.$file->getClientOriginalExtension();
$file = File::resize($file);
$this->attachment_path = $folder_name.'/'.$file_name;
Storage::disk(config('app.filesystem_driver', ''))->put($this->attachment_path, $file);
$this->save();
}
public function createFileName()
{
$file_name = 'po_'.$this->customer->code.'-'.$this->customer->id.'_'.$this->po_number.'-'.$this->id;
return $file_name;
}
My File helper code
public static function resize($file)
{
$resized_file = $file;
if (strtolower($resized_file->getClientOriginalExtension()) != 'pdf') {
// resize file if it is not pdf (file is photo)
// get image size then resize largest size to size limit - dont upsize if image is smaller than max size
list($width, $height) = getimagesize($resized_file);
if ($width > $height) {
$resized_file = Image::make($resized_file)->resize(config('app.max_image_width', ''), null, function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->encode($resized_file->getClientOriginalExtension(), 60);
} else {
$resized_file = Image::make($resized_file)->resize(null, config('app.max_image_width', ''),function ($constraint) {
$constraint->aspectRatio();
$constraint->upsize();
})->encode($resized_file->getClientOriginalExtension(), 60);
}
}
return $resized_file;
}
public static function removeFiles($file_name, $ext_included = FALSE)
{
if ($ext_included == TRUE) {
// remove specific file
if (Storage::disk(config('app.filesystem_driver', ''))->exists($file_name)) {
Storage::delete($file_name);
}
} else {
// remove file with any extension
$ext = array('.pdf', '.jpg', '.jpeg', '.gif', '.png');
for ($cnt = 0; $cnt <= 4; ++$cnt) {
if (Storage::disk(config('app.filesystem_driver', ''))->exists($file_name.$ext[$cnt])) {
Storage::delete($file_name.$ext[$cnt]);
}
}
}
}
I realize the code may be a little confusing use the env variables but I'm trying to limit the pain in the event I need to change the folder name or move the files outside of the app. The application will have very few users maybe 3 or 4 and I don't anticipate a lot of files being uploaded which is why I'm storing the files in the application structure.
This is my first Laravel app and I put this code together using the docs and many a many different tutorials. It took a while but eventually I got it to work for images. So if you see things that don't look standard or good practice I welcome any pointers.
Thanks for taking the time to read this, any help is appreciated!
I had to use two different approaches to saving files in the system based on if the file was an image or pdf. I do some processing (resizing) on images before putting them into my storage folders with Intervention Image. This in turn returns a different object type than the raw uploaded file, because of this some of the commands to add the file (after processing) will not work.
So if I'm storing a pdf file I use:
$file->storeAs($folder_name, $file_name, config('app.filesystem_driver', ''));
If I'm storing an image that I have used Intervention Image on then I use:
Storage::disk(config('app.filesystem_driver', ''))->put($this->attachment_path, $file);
I couldn't find one command that worked for both so I just check the extension before storing. Not sure if this is the "right way" but it got the job done.

writing content of local file to blob using javascript

I am trying to upload an excel file(named test1.xls) present in my computer in c drive at location->C:\test\test1.xls to google site(https://sites.google.com/xyz).To do so, I am using Google script editor and code shown below. The issue is that I am not able to pass the contents of file test1.txt at location C:\test\test1.txt instead of the text ("Here is some data")shown in code line shown below(var blob = Utilities.newBlob("Here is some data", "text/plain", "test1.xls");).Also what needs to be given instead of "text/plain" as it is excel file.Please let me know how to do that with code as I am new to google scripting/api coding,many thanks in advance.
CODE->
function doPost(e) {
var site = SitesApp.getSiteByUrl("https://sites.google.com/xyz"); Logger.log(site.getName());
var page = site.getChildren()[0];
// Create a new blob and attach it. Many useful functions also return
// blobs file uploads, URLFetch
var blob = Utilities.newBlob("Here is some data", "text/plain", "test1.xls");
try {
// Note that the filename must be unique or this call will fail
page.addHostedAttachment(blob);
}
catch(e){
Logger.log('Hosted attachment error msg:' +e.message);
}
}

Appcelerator Titanum Delete File in tmpdirectory

I am using Appcelerator Titanium 3.0.2 to allows user to watch/download videos&audios. Here is part of code to get the file object and play the audio.
var filename = self.url.substring(self.url.lastIndexOf('/')+1);
var file = Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory,filename);
if(!file.exists())
self._download(self.url, filename, Ti.Filesystem.tempDirectory, function(){
setAudUrl(file.nativePath);
timeBar.max = audPlayer.duration*1000;
prgHandle = setInterval(updateProgressBar,10000);
audPlayer.play();
audCtrlBar.show();
loading.hide();
},
function(_progress,_position){
httpClient=_position;
loading.show();
},
function(){
noLabel.show();
loading.hide();
});
else {
setAudUrl(file.nativePath);
timeBar.max = audPlayer.duration*1000;
prgHandle = setInterval(updateProgressBar,10000);
audPlayer.play();
audCtrlBar.show();
}
This code is working, but my question is how to remove the file when the user exist the app. Since Apple required that file in /tmp directory will be removed after user exist the app. Anyone can help? Thanks.
You could use Titanium's application events pause and paused. They are called when the app becomes inactive but this only works on iOS.
Titanium.App.addEventListener('pause' /* or paused, see docs */, function() {
var dir = Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory, 'tmpDownloads'); // ensure that you use the same folder for storing the downloaded files. A separate folder is easier to remove.
if(dir.exists() && dir.isDirectory()) {
dir.deleteDirectory(true); // true removes recursively the directory and its contents
}
});
You need to create the directory again when resume-ing the app.