I have an app which stores music from user. User can upload multiple files at once. But while adding this code, the database and the controller only uploads the first file, discarding other files. I need to solve this problem. Any solutions?
UploadController.php
public function store(Request $request)
{
//This is a complex way to store user id. If any easy way, then help me.
$curruser = auth()->user();
$userid = $curruser->id;
$songs = $request->file('songs');
$paths = [];
if(!empty($songs)){
foreach ($songs as $song){
$filename = $song->getClientOriginalName();
$filesize = $song->getSize();
$extension = $song->getClientOriginalExtension();
$paths[] = $song->storeAs('songs',$filename);
$path = new MusicUpload(array(
'user_id' => $userid,
'filename' => $filename,
'extension' => $extension,
'filesize' => $filesize,
));
$path->save();
$paths[] = $path;
return redirect('/fileupload')->with('success','Uploaded successfully');
}
}
}
And also I cannot store the location of the file in the mysql server. Any ideas to do that also. Thanks
Use this
public function store(Request $request)
{
$input = $request->all();
$rules = array(
'songs.*' => 'required|mimes:jpeg,png,jpg,doc,docx,pdf,mp4,mov,ogg,qt', //etc
);
$validator = Validator::make($input, $rules);
if ($validator->fails()) {
$arr = array("status" => 400, "message" => $validator->errors()->first(), "data" => array());
} else {
try {
$datas = [];
$result = [];
if ($request->hasfile('songs')) {
foreach ($request->file('songs') as $key => $file) {
$name = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$filesize = $file->getSize();
$input['songs'] = time() .uniqid().'.' . $file->getClientOriginalExtension();
$file->move(public_path() . '/images', $input['songs']); // your file path
$datas[$key] = $name;
$datas[$key] = $extension;
$datas[$key] = $filesize;
$file = new MusicUpload();
foreach ($datas as $data) {
$file->user_id = Auth::user()->id;
$file->filename = $name;
$file->extension = $extension;
$file->filesize = $filesize;
$file->save();
}
}
}
$arr = array("status" => 200, "message" => "success", "data" => $output);
} catch (\Exception $ex) {
if (isset($ex->errorInfo[2])) {
$msg = $ex->errorInfo[2];
} else {
$msg = $ex->getMessage();
}
$arr = array("status" => 400, "message" => $msg, "data" => array());
}
}
return \Response::json($arr);
}
Just return the redirection after foreach loop has completed.
public function store(Request $request)
{
//This is a complex way to store user id. If any easy way, then help me.
$curruser = auth()->user();
$userid = $curruser->id;
$songs = $request->file('songs');
$paths = [];
if(!empty($songs)){
foreach ($songs as $song){
$filename = $song->getClientOriginalName();
$filesize = $song->getSize();
$extension = $song->getClientOriginalExtension();
$paths[] = $song->storeAs('songs',$filename);
$path = new MusicUpload(array(
'user_id' => $userid,
'filename' => $filename,
'extension' => $extension,
'filesize' => $filesize,
));
$path->save();
$paths[] = $path;
}
return redirect('/fileupload')->with('success','Uploaded successfully');
}
}
Related
for the reusability, I plan to split my function into two functions. Basically, the concept of the function is loads the input file then preview the data.
Working Code
public function uploadImportCsv()
{
$file = Input::file('file');
$extension = $file->getClientOriginalExtension();
$filename = sha1($file->getClientOriginalName().time()) . ".{$extension}";
//upload to s3
#doing upload to s3
$data = [
'title'=>[],
'value'=>[]
];
$results = Excel::load(Input::file('file'), function($reader){
})->get();
foreach ($results as $result) {
foreach ($result as $key => $value) {
if(!in_array($key, $data['title'])){
array_push($data['title'], $key);
}
}
array_push($data['value'], $result);
}
return Response::json(['filename' => $filename, 'data' => $data]);
}
after split
public function previewCsv()
{
//Preview table
$data = [
'title'=>[],
'value'=>[]
];
$results = Excel::load(Input::file('file'), function($reader){
})->get();
foreach ($results as $result) {
foreach ($result as $key => $value) {
if(!in_array($key, $data['title'])){
array_push($data['title'], $key);
}
}
array_push($data['value'], $result);
}
return Response::json(['data' => $data]);
}
public function uploadImportCsv()
{
$file = Input::file('file');
$extension = $file->getClientOriginalExtension();
$filename = sha1($file->getClientOriginalName().time()) . ".{$extension}";
//upload to s3
#doing upload to s3
$data = $this->previewCsv();
return Response::json(['filename' => $filename,'data' => $data]);
}
I called the function from the preview function but it does not work.
If you need same result, it's not necessary to return a json object from previewCsv funtion.
public function previewCsv()
{
....
return $data;
}
I was trying to update my userprofile with the following controller but the problem is if i update only profile picture it shows the above error..But if i update every value it update successfully. How do i update the userProfile without updating every value :
public function updateUser(Request $request)
{
$this->validate($request, [
'profile_picture' => 'dimensions:width=400,height=400',
'cover_picture' => 'dimensions:width=800,height=400',
'avatar' => 'dimensions:width=80,height=80',
]);
if (\Auth::check())
{
$user= User::find(\Auth::id());
}
$files= [];
if($request->file('profile_picture')) $files[] = $request->file('profile_picture');
if($request->file('cover_picture')) $files[] = $request->file('cover_picture');
if($request->file('avatar')) $files[] = $request->file('avatar');
foreach($files as $file)
{
if(!empty($file))
{
$filename = time().str_random(20). '.' . $file->getClientOriginalExtension();
$file->move('users/',$filename);
$filenames[]=$filename;
}
}
$user->profile_picture = $filenames[0];
$user->cover_picture = $filenames[1];
$user->avatar = $filenames[2];
$user->save();
return redirect::back()->with('Warning',"Profile Updated Successfully");
}
I don't think it's wise using a positional array like this, As you've discovered, what if someone only wants to update their avatar. I feel your assignment into $files[] is redundant and you could go straight into your processing code.
Basically your current implementation means $files can be of a variable length, how do you know which is 0, 1 or 2 etc ?
With my approach, the code is now looping over each type of picture, and assigns it into the user with $user->$type directly by the same matching type property.
foreach( array( 'profile_picture', 'cover_picture', 'avatar' ) as $type)
{
if( $request->file( $type ) )
{
$filename = time() . str_random(20) . '.' . $request->file( $type )->getClientOriginalExtension();
$request->file( $type )->move( 'users/', $filename );
$user->$type = $filename;
}
}
If you find you need to map a different $source to the $type variable, you could do this with an additional array index...
foreach( array(
'profile_picture' => 'profile_picture',
'cover_picture' => 'cover_picture',
'avatar' => 'avatar'
) as $source => $type)
{
if( $request->file( $source ) )
{
$filename = time() . str_random(20) . '.' . $request->file( $source )->getClientOriginalExtension();
$request->file( $source )->move( 'users/', $filename );
$user->$type = $filename;
}
}
I finally came up with a solution mate.
You can try to Include a var_dump of $filenames. I suppose that $filenames[1] doesn't exist at all.
I'm trying to save array of multi images and values , the values was saving well but when i going to add image it's only save one image and upload only one .
Here's my controller function
public function store(Request $request) {
$parentproduct = new Product();
$parentproduct->id = Input::get('id');
$parentproduct->save();
$insertedId = $parentproduct->id;
$uploadcount=0;
$files = Input::file('main_image');
$file_count = count($files);
foreach($files as $i=>$file) {
$multiupload=new ProductsTranslation();
if($request->hasFile('main_image')){
$destinationPath = 'website/images';
$filename = $file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);
$uploadcount ++;
$multiupload->main_image = $filename;
$multiupload->id = $request->input('id')[$i];
$multiupload->title = $request->input('title')[$i];
$multiupload->language = $request->input('language')[$i];
$multiupload->product_id=$parentproduct->id;
$multiupload->save();
}
}
It's working fine after the final update ...
try this:
if (Input::hasFile('main_image')) {
foreach (Input::file('main_image') as $file) {
$destinationPath = 'website/images';
$filename = $file->getClientOriginalName();
$upload_success = $file->move($destinationPath, $filename);
$uploadcount ++;
// You have to initialize your array out side your loop
$insertprod = [];
foreach ($request->input('language') as $i=>$language) {
$insertprod[] = array(
'id' =>$request->input('id')[$i],
'product_id'=>$parentproduct->id,
'title' =>$request->input('title')[$i],
'language' => $request->input('language')[$i],
//used this line to save the image name path !
'main_image'=>$filename[$i]
);
}
}
DB::table('products_translations')->insert($insertprod);
}
i am trying yo create a new file using a existing file.
but When i create a new file in my uploads folder a file is automatically created with resource id #3 WHY??
public function edit_ini_custom($id)
{
/*Getting parameters name to display in view*/
$this->data['params'] = $this->parameter_m->get();
/*Path of our BASE and CUSTOM INI files*/
$path = "./uploads/";
$this->db->select('*');
$this->db->where('id',$id);
/*Here the id is the ID we got from URI View*/
$this->db->from('base_ini');
$query = $this->db->get();
$result = $query->row();
$filename= $result->base_ini_filename;
$path= $result->file_path;
/*Reading Contents from our path and the name of file we got from database*/
file_get_contents($path.$filename);
$this->data['parameters'] = parse_ini_file($path.$filename);
/*Getting Our POST DATA from View*/
$data = array(
'SipUserName' => $this->input->post('SipUserName') ,
'SipAuthName' => $this->input->post('SipAuthName'),
'DisplayName' => $this->input->post('DisplayName'),
'Password' => $this->input->post('Password'),
'Domain' => $this->input->post('Domain'),
'Proxy' => $this->input->post('Proxy'),
'Port' => $this->input->post('Port'),
'ServerMode' => $this->input->post('ServerMode'),
'Param_1' => $this->input->post('Param_1'),
'Param_2' => $this->input->post('Param_2')
);
$this->load->helper('file');
$suffix =$this->input->post('SipUserName');
/*Setting the Name of File*/
$name =$this->session->userdata('username');
/*Creating New file with the name of customer loggedin*/
$file_new = fopen('uploads/'.$name.$suffix.'.ini', 'w');
fwrite($file_new, "[INIDetails]\n");
foreach ($data as $key => $value)
{
fwrite($file_new, " $key = $value\n");
}
fclose($file_new);
/*Setting path to New CUSTOM file with customer name as prefix*/
$file = $path.$file_new;
function write_php_ini($array, $file)
{
$res = array();
foreach($array as $key => $val)
{
if(is_array($val))
{
$res[] = "[$key]";
foreach($val as $skey => $sval) $res[] = "$skey = ".(is_numeric($sval) ? $sval : '"'.$sval.'"');
}
else $res[] = "$key = ".(is_numeric($val) ? $val : '"'.$val.'"');
}
safefilerewrite($file, implode("\r\n", $res));
}
function safefilerewrite($fileName, $dataToSave)
{ if ($fp = fopen($fileName, 'w'))
{
$startTime = microtime(TRUE);
do
{ $canWrite = flock($fp, LOCK_EX);
// If lock not obtained sleep for 0 - 100 milliseconds, to avoid collision and CPU load
if(!$canWrite) usleep(round(rand(0, 100)*1000));
} while ((!$canWrite)and((microtime(TRUE)-$startTime) < 5));
//file was locked so now we can store information
if ($canWrite)
{ fwrite($fp, $dataToSave);
flock($fp, LOCK_UN);
}
fclose($fp);
}
}
/*Creates ini file, dumps array to string and creates .INI file*/
write_php_ini($data,$file);
/*Back to you index page id data is submmited*/
if(isset($_POST['submit'] ))
{
redirect('customer/upload_ini/index');
}
$this->data['subview'] = 'customer/upload/edit_ini_custom';
$this->load->view('customer/_layout_main', $this->data);
}
Can someone explain to me why I cannot delete the images that I was able to successfully import in the first half of the function
function delete_files($target) {
foreach(glob($target.'*.*') as $v){
unlink($v);
}
}
function importImagesforSlideShow()
{
$array = $_REQUEST["data"];
$slidePath = '../../images/carousel-slides/';
$url = $array[0];
$images = $array[1];
$imageExtQualifier = $array[2];
if (!file_exists($slidePath)) {
mkdir($slidePath, 0777, true);
}
foreach ($images as $imageName) {
$context = stream_context_create(array(
'http' => array(
'ignore_errors' => true,
'header' => "User-Agent:MyAgent/1.0\r\n"
)
));
$urlLoc = $url . $imageName . $imageExtQualifier;
$img = $imageName . '.jpg';
file_put_contents($slidePath . $img, file_get_contents($urlLoc, FALSE, $context));
}
// not working
delete_files(__DIR__ . $slidePath);
echo json_encode($images);
}
UPDATE:
Salty: I think you are on to something. This does nto look right
G:\PleskVhosts\abc.com\xyz.com\scripts\php../../images/carousel-slides/
it should be something like:
G:\PleskVhosts\abc.com\xyz.com\images/carousel-slides/
How to fix?