I'm working on a mobile application, and I'm handling database and APIs.
Android developer is sending me images and I'm using file function to get its data.
I have written this code:
public function addalbum($baseurl)
{
$images = array();
if(isset($_FILES['image'])){
//echo "hellow";exit;
//$pathToUpload = '../media/gallary/';
$count = count($_FILES['image']['name']);
//echo $count;exit;
$imagepaths = '';
$imagetepaths = '';
$images = '';
for($i=0;$i<$count;$i++){
$imageurls[$i] = $baseurl."../media/gallary/".$_FILES['image']['name'];
$imagepaths = '../media/gallary/'.$_FILES['image']['name'][$i];
$images[$i] = $_FILES['image']['name'][$i];
$imagetepaths = $_FILES['image']['tmp_name'][$i];
move_uploaded_file($imagetepaths , $imagepaths);
}
}
$data=array(
'image' => ($images != '') ? implode(',',$imageurls) : '',
'email'=>$this->input->post('email'),
'name'=>$this->input->post('name'),
'type'=>$this->input->post('type')
);
//print_r($data);exit;
$this->db->insert('album',$data);
}
But from the bunch of images, only the last one is being inserted in the database.
any help will be very much appreciated.
Thanks
$_FILES['image'] is the field name of 1 uploaded file. If multiple files should be posted you would require different names for each field. Just think how will you upload multiple files from an html form.
For example: $_FILES['image1'], $_FILES['image2'], $_FILES['image3']
You could use something like this:
if(is_array($_FILES)) {
foreach($_FILES as $fileKey => $fileVal){
if($fileVal[name]) {
move_uploaded_file($_FILES["uploaded_file"]["tmp_name"],$target_path.$fileVal[name]);
}
}
}
Checkout this example where a maximum of 3 files are uploaded from android using php.
Related
i am trying to do an update using dynamic for "education history" but there is an image also, i use eloquent to update too, for some reason the data is saved in the database but the image just tmp and cannot find in the folder.
//count array data inputed
for($incs=0; $incs < count($data_detail_user['institution_names']); $incs++) {
// update education
foreach( $data_detail_user['institution_names'] as $key => $file ){
// get old photo thumbnail
$get_photo = Educations::where('id', $key)->first();
// store photo
$path = $file->store(
'assets/education/thumbnail', 'public'
);
$education_user = Educations::find($incs);
$education_user->detail_user_id = $detail_user['id'];
$education_user->name = $data_detail_user['institution_names'][$incs];
$education_user->course = $data_detail_user['education_courses'][$incs];
$education_user->start = $data_detail_user['education_starts'][$incs];
$education_user->graduate = $data_detail_user['education_graduates'][$incs];
$education_user->address = $data_detail_user['education_addresses'][$incs];
$education_user->regencies = $data_detail_user['education_regencies'][$incs];
$education_user->provinces = $data_detail_user['education_provinces'][$incs];
$education_user->country = $data_detail_user['education_countries'][$incs];
$education_user->zip_code = $data_detail_user['education_zips'][$incs];
$education_user->certificate = $data_detail_user['education_certificates'][$incs][$path];
$education_user->save();
$data_detail_user = 'storage/' .$get_photo['certificate'];
if (File::exists($data_detail_user)) {
File::delete($data_detail_user);
} else {
File::delete('storage/app/public/' .$get_photo['certificate']);
}
}
}
[the error show Call to a member function store() on string]
this is the screenshoot of the error
[1]: https://i.stack.imgur.com/l96sm.png
$path = $request->file('path')->store('public/post');
I assume you have a directory where the image is suppose to be stored that's why i created the post directory after public.
im trying to upload multiple images with laravel 5.4, actually the process to upload images is done, the question is how to store them in database?
for example when gonna create a slide show of something that has several images that is uploaded, how to group them so the slide show knows those images are in one group?
can you guys help me?
Make sure you go to config/filesystems and turn 'FILESYSTEM_DRIVER' to 'public'
Model to store image paths:
class UserDocuments extends Model
{
//
protected $table = 'user_documents';
public function store($user_id, $document_link, $file_name)
{
$this->user_id = $user_id;
$this->document_link = $document_link;
$this->file_name = $file_name;
$this->save();
}
}
Code in controller to store files ('document' is file input field name)
if ($request->hasFile('document')) {
$link = $request->file('document')->store('documents');
}
$userDocuments->store(request('user_id'), url($link), $link);
To show if the images are in a group, you would have to create a database column called 'group_id' and sort them accordingly.
We have to store images into one records/row by separting commas.
class DocumentController extends Controller
{
public function store(Request $request)
{
$pid = $request->input('pid');
$input = $request->file('files');
$picture = array();
if($request->hasFile('files')) :
foreach ($images as $item):
$extension = $item->getClientOriginalName(); //image extension
$name = time() . '.' .$extension; //image name
$item->move('uploads/documents/', $name); //move to destination
$arr[] = $name; //store image into array
endforeach;
$picture = implode(",", $arr); //Image separated by comma
else:
$picture = '';
endif;
DB::table('document')->insert(array('pid' => $pid,'image' => $picture));
Session::flash('message', 'Multiple Images are uploaded successfully');
return redirect('/multiple-image');
}
}
Hi I have created a script to download images and to rename from a url. The links and name are stored in a database. The database looks like this:-
id name url
1 abcd http://www.abcd.com/a.jpeg
I am running a following script to download and renaming the images.:-
$sql = "SELECT * FROM data";
$results = $gtl->query($sql);
while($row = $results->fetch_assoc()) {
$n = $row['name'];
$url = $row['url'];
$name = $n.'.jpeg';
$path = "images/";
if ($url != NULL) {
$get_image = file_get_contents($url);
if ($http_response_header != NULL) {
$get_file = $path . $name;
file_put_contents($get_file, $get_image);
}
}
The following code works well but consumes a lot of time. I have tried using cURL but it has similar speed. Since there are over 300 images that needs to be downloaded. It would be a great if anyone can suggest a way to fasten the process. Any help is highly appreciated.
I'm trying to create a moodle profile field plugin for file upload.
my edit_field_add in field.class is:
function edit_field_add(&$mform) {
$maxlength = 1024*1024;
$fieldtype = $this->field->param2;
/// Create the form field
$mform->addElement('filepicker', $this->inputname, format_string($this->field->name), null,
array('maxbytes' => $maxlength, 'accepted_types' => $fieldtype));
$mform->setType($this->inputname,PARAM_FILE);
}
This shows and saves file correctly but
Saves a number in data field of plugin (e.g. 766686554)
How can I find the URL to the uploaded file to make a link to it by display_data in 'field.class` ?
EDIT
I'm saving the file by this:
function edit_save_data_preprocess($data, &$datarecord) {
$draftitemid=file_get_submitted_draft_itemid($this->inputname);
if (empty($entry->id)) {
$entry = new stdClass;
$entry->id = 0;
}
$context = context_user::instance($this->userid);
file_save_draft_area_files($draftitemid, $context->id, 'profile_field_fileupload', $this->inputname,$entry->id);
return $draftitemid;
}
But draft still exists and I cant find how to retrieve saved file!
Assuming you have saved the file after the form has been posted -http://docs.moodle.org/dev/Using_the_File_API_in_Moodle_forms#filepicker
Then you can use the File API to retrieve the file(s) - http://docs.moodle.org/dev/File_API#Serving_files_to_users
eg to display links to all files for the plugin:
$out = array();
$fs = get_file_storage();
$files = $fs->get_area_files($contextid, $pluginname, $pluginfolder);
foreach ($files as $file) {
$filename = $file->get_filename();
$url = moodle_url::make_file_url('/pluginfile.php', array(
$file->get_contextid(),
$pluginname,
$pluginfolder,
$file->get_itemid(),
$file->get_filepath(), $filename)
);
$out[] = html_writer::link($url, $filename);
}
$br = html_writer::empty_tag('br');
echo implode($br, $out);
Language: PHP / MySQL
I am going out of my mind, I really have to ask now... I have a multiple file upload form:
<input type="file" name="fileupload[]" multiple>
With the help of some Javascript, on each change made to this input, it appends a list of filenames, + a formatted string (grabbed from the filename) inside another input, so onchange we have a layout as shown below (assuming that we just added some images):
Almost similar to: http://jsfiddle.net/pxfunc/WWNnV/4/
// An HTML representation of such layout would be... (assuming that we added 3 images)
<input type="file" name="fileupload[]" multiple>
image-name-1.jpg <input type="text" value="Image Name 1" name="keyword[]">
justsome_file.png <input type="text" value="Justsome File" name="keyword[]">
some_Img-031.gif <input type="text" value="Some Img 031" name="keyword[]">
<input type="submit" value="Upload">
I have it this way because aside from uploading the files, I would also like to add them to my database, with a default title based on its filename (and the option to set/change this title for each image as I upload it). There is no problem with my form.
PROBLEM: My dilemma lies inside the PHP page where the form data/action is submitted.
I can only manage to either:
Upload correct images, but get same title for all
Insert correct titles, but get same image for all
Here is my PHP action page: (Currently uploading correct images, but having same title for all)
<?php
// CONNECT TO DATABASE...
// INCLUDE UPLOAD CLASS LIBRARY
include (dirname(__FILE__).'/lib/class.upload.php');
$files = array();
foreach ($_FILES['fileupload'] as $k => $l)
{
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
}
}
// create an array here to hold file names
$uploaded = array();
foreach ($files as $file)
{
$generate_name = rand(100,99999);
$generate_name_extra = rand(200,9999);
$filenamex = "COVER_PHOTO_".$generate_name.$generate_name_extra."_".time();
$filenamex_thumb = $filenamex."_thumb";
$handle = new upload($file);
if ($handle->uploaded) {
$this_upload = array();
///// 1 ////////////////////////////////////////////////////////////////////
$handle->file_new_name_body = $filenamex_thumb;
$handle->file_force_extension = true;
$handle->image_resize = true;
$handle->image_x = '300';
$handle->image_ratio_y = true;
$handle->jpeg_quality = '100';
// ABSOLUTE PATH BELOW
$handle->process($absoRoot.'covers/thumbs/');
////////////////////////////////////////////////////////////////////////////
if ($handle->processed) {
// store the image filename
$this_upload['image'] = $handle->file_dst_name; // Destination file name
$this_upload['body'] = $handle->file_dst_name_body; // Destination file name body
$this_upload['extension'] = $handle->file_dst_name_ext; // Destination file extension
$category_id = $_POST['cat'];
$hiddenvalues = explode ("|",$_POST["cat"]);
$category = $hiddenvalues[0];
$category_name = $hiddenvalues[1];
$sql = 'INSERT INTO cover (id, img, keyword, category_name, cat_id) VALUES ("", "'.$this_upload['image'].'", "'.$imagename.'", "'.$category_name.'", "'.$category.'")';
mysql_query($sql);
}
$handle->clean();
header("Location: ./upload.php");
$message = "";
} else {
echo ' file not uploaded to the wanted location';
echo ' Error: ' . $handle->error . '';
}
} ?>
(I use the Upload Class by Colin Verot to handle image uploads, and their FAQ tutorial to handle MULTIPLE image uploads on this page, under: What about multiple uploads?)
This would work perfect if I were just uploading images, however I added the functionality of adding each image data to my database. & This is where it gets confusing.
I'm sure the key is placing the SQL query inside the right foreach, or perhaps making another one, but I've tried that & it only gives me 1 good result for either the image upload or the title, never for both.
I need to upload the image to the site, then store its data (including image path) to my database.
Please look into my code and enlighten me how to solve this problem? A snippet clue would really be great for now as I am already very confused after having tried all I could think of. Thank you so much!
You aren't saving your $imagename variable to the $files array, you're just resetting it each time.
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
Should be something like:
$files[$i][$k] = array($v, $_POST['keyword'][$i]);
...
foreach ($files as $data) {
list($file, $imagename) = $data;
...
}
I do think one of your problems is your foreach:
$files = array();
foreach ($_FILES['fileupload'] as $k => $l)
{
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$imagename = $_POST['keyword'][$i];
}
}
So you are going through each of the fields assigning their value to the right file which fits this structure policy:
_FILES => array(
'name' => array(0 => 'file.txt'),
'size' => array(0 => 235)
)
Which is correct for multifiles but then you do:
$imagename = $_POST['keyword'][$i];
Which does not look right. You are overwriting the var each time with the last looked at which means you will only ever get one input vlaue.
When you're gathering the file information you're overwriting $imagename on every loop so it will be assigned to the last one. Try attaching it to the $files variable (hopefully this doesn't mess with the upload class you're using).
foreach ($l as $i => $v)
{
if (!array_key_exists($i, $files))
$files[$i] = array();
$files[$i][$k] = $v;
$files[$i]['imagename'] = $_POST['keyword'][$i];
}
Then update your $sql string to reference that
$sql = 'INSERT INTO cover (id, img, keyword, category_name, cat_id)
VALUES ("", "'.$this_upload['image'].'", "'.$file['imagename'].'",
"'.$category_name.'", "'.$category.'")';