I have found this script http://d.danylevskyi.com/node/7 which I have used as a starter for the below code.
The goal is to be able to save a user picture:
<?php
define('DRUPAL_ROOT', getcwd());
require_once DRUPAL_ROOT . '/includes/bootstrap.inc';
drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL);
$uid = 99;
$account = user_load($uid);
// get image information
$image_path = 'public://avatars/upload/b8f1e69e83aa12cdd3d2babfbcd1fe27_4.gif';
$image_info = image_get_info($image_path);
// create file object
$file = new StdClass();
$file->uid = $uid;
$file->uri = $image_path;
$file->filemime = $image_info['mime_type'];
$file->status = 0; // Yes! Set status to 0 in order to save temporary file.
$file->filesize = $image_info['file_size'];
// standard Drupal validators for user pictures
$validators = array(
'file_validate_is_image' => array(),
'file_validate_image_resolution' => array(variable_get('user_picture_dimensions', '85x85')),
'file_validate_size' => array(variable_get('user_picture_file_size', '30') * 1024),
);
// here all the magic :)
$errors = file_validate($file, $validators);
if (empty($errors)) {
file_save($file);
$edit['picture'] = $file;
user_save($account, $edit);
}
?>
A picture is created in sites/default/files/pictures/ with the name picture-99-1362753611.gif
Everything seems correct in the file_managed table except that:
the filename field is empty
the uri field shows public://avatars/upload/b8f1e69e83aa12cdd3d2babfbcd1fe27_4.gif
the status field is set to 0 (temporary)
The picture field in the users table gets updated with the fid of the above mentioned entry.
I would guess that the file_managed table should store the final file (in sites/default/pictures) instead of the original file info and that the users table should link to the one too.
Any idea how I can achieve that? I am quite new to the Drupal API. Thank you.
Edit:
I understand that I am giving the original file to the file_save and user_save functions. But which one actually creates the file in sites/default/pictures/ ?
Try adding the following to your code:
$file->filename = drupal_basename($image_path);
$file->status = FILE_STATUS_PERMANENT;
$file = file_save($file); // Use this instead of your current file_save
Does that help?
------------------ EDIT ------------------
If you want to save a copy of the file in a new location, you can replace the third line above with something like
// Save the file to the root of the files directory.
$file = file_copy($file, 'public://');
Related
I have a controller which handles the upload functionality of the music file. The controller uses this Laravel getID3 package to parse the metadata from the music file and store in the database.
My code looks like this
if($request->hasfile('songs')){
foreach ( $request->file('songs') as $key => $file){
$track = new getID3($file);
$tifo = $track->extractInfo();
$artistName = $track->getArtist();
$songName = $track->getTitle();
$albumName = $track->getAlbum();
$extension = $track->getFileFormat();
$thumbnail = $track->getArtwork(true);
$thumbnails = 'artwork-'.time().'.'.$thumbnail->getClientOriginalExtension();
$location = time() .uniqid().'.' . $extension;
$file->storeAs('public/songs',$location);
//$file->storeAs('public/sthumbs',$thumbnails);
$file = new MusicUpload();
$music_upload_file = new MusicUpload();
$music_upload_file->user_id = Auth::user()->id;
$music_upload_file->filename = $songName;
$music_upload_file->extension = $extension;
$music_upload_file->artistname = $artistName;
$music_upload_file->albumname = $albumName;
$music_upload_file->location = $location;
$music_upload_file->thumbnail = $thumbnails;
$music_upload_file->save();
}
}
What I want to do is to store both the music file as well as the thumbnail of the file in the database.
Here the $thumbnails will store the image in the specified folder but the image is unreadable, i.e. it has the same file size as the music and doesn't contain the artwork which is to be stored and retrieved.
If I don't include the $thumbnails part, the package default stores to the temp folder which is inaccessible to the controller.
So how do I write the code such that the thumbnail(artwork) of the music gets stored in the correct folder and it can display the output too.
You can store it to storage folder.
Storage::disk('public')->put($location,File::get($file));
Don't forget to run php artisan storage:link
I have a function that saves the image in the respective folder.
I want to check if the image already exist in the folder , first with name if the name are same then with the SHA1 of the image
My current function looks something like this
function descargarImagen($id,$url,$pais1)
{
$ruta = rutaBaseImagen($id,$_POST['pais']);
$contenido = file_get_contents($url);
$ext = explode('.', $url);
$extension = $ext[count($ext) -1];
$imagen['md5'] = md5($contenido);
$imagen['sha1'] = sha1($contenido);
$imagen['nombre'] = $imagen['md5'].'.'.$extension;
$ficherof = $pais[$pais1]['ruta_imagenes'].'/'.$ruta.'/'.$imagen['nombre'];
$ficherof = str_replace('//', '/', $ficherof);
//Here before putting the file I want to check if the image already exist in the folder
file_put_contents($ficherof, $contenido);
$s = getimagesize($ficherof);
$imagen['mime'] = $s["mime"];
$imagen['size'] = $s[0].'x'.$s[1];
$imagen['url'] = $urlbase_imagenes.'/'.$ruta.'/'.$imagen['nombre'];
$imagen['url'] = str_replace('//', '/', $imagen['url']);
$imagen['date'] = time();
$imagen['fichero'] = $ficherof;
return $imagen;
}
I am trying to validate in two ways
1.If the name of the image is present in the folder or not .
2.If present then check if the image is same or different , because there could be new image but same name
Any suggestion will be appreciated
Thanks in Advance
You can use this,
// Check if file already exists
if (file_exists($target_file)) {
//echo "Sorry, file already exists.";
/**
* validate images that are different but have same name
* we can use base64_encode function to compare the old and new image
* basics: http://php.net/manual/en/function.base64-encode.php
* online conversion help: http://freeonlinetools24.com/base64-image
*/
$base64_encoded_new_image=base64_encode(file_get_contents($name_of_your_new_image_that_you_want_to_upload));
$base64_encoded_old_image=base64_encode(file_get_contents($name_of_the_image_that_already_exists));
if ($base64_encoded_new_image!=$base64_encoded_old_image) {
/** so the images are actually not same although they have same name
* now do some other stuffs
*/
}
}
for more information please visit http://www.w3schools.com/php/php_file_upload.asp
The hint given by this comment:
//Here before putting the file I want to check if the image already exist in the folder
makes me think you're asking for file_exists, which is the first thing that's shown if you search for "php file exist" in any search engine...
I have a custom content type with 2 custom fields: file (file) and list (status).
I can set the value of status by doing:
$node = node_load($n, $r);
$node->field_status[$node->language][0]['value'] = 1;
node_save($node);
I want to create entries for field_file and file_managed (core table) for a file that is ALREADY on the server. I already know the MIME type, size and path of the file.
What is the proper way to achieve this?
I would instantiate the file object manually and use file_save() to commit it (using an image file as an example):
global $user;
$file = new stdClass;
$file->uid = $user->uid;
$file->filename = 'image.png';
$file->uri = 'public://path/to/file/image.png';
$file->status = 1;
$file->filemime = 'image/png';
file_save($file);
You should then call file_usage_add() to let Drupal know your module has a vested interest in this file (using the nid from your $node object):
file_usage_add($file, 'mymodule', 'node', $node->nid);
Finally you can add the file to the node:
$node->field_file[$node->language][] = array(
'fid' => $file->fid
);
Hope that helps
i have a question that how to get name of a directory that is dynamically created?
explanation-:
i create a file upload type and one submit button whenever i clicked submit button then directory is created if not exist with logged in username. but file is not stored there because i can't get a name of directory to store that file.
i want how to get that name which function is used in php to get name of directory that is created dynamically.
//$image = $_GET['upload'];
$upload = $_POST["submit"];
session_start();
$_SESSION['x'] = "username";
$path = "upload/";
$image_name = $_FILES["upload"]["name"];
$temp = $_FILES["upload"]["tmp_name"];
if(isset($upload)){
mkdir($path.$_SESSION['x']);
$new = ""//what function I used here to fetch the name of directory in last step
move_uploaded_file($temp,$new.$image_name);
}
The directory name is $path.$_SESSION['x'].
I have to send a file to an API. The API documentation provides an example of how to do this through a file upload script ($_FILES). But, I have the files on the same machine, so would like to skip this step and just read in the file directly to save time.
How can I read in the file (a video) so that it will work with this code snippet?
I understand that FILES is an array, but I could set the other parts of it (the filename) seperately, I just really need the data part of it to be read in the same format to work with this code (do I use fread? file get contents?)
<?php
# Include & Instantiate
require('../echove.php');
$bc = new Echove(
'z9Jp-c3-KhWc4fqNf1JWz6SkLDlbO0m8UAwOjDBUSt0.',
'z9Jp-c3-KhWdkasdf74kaisaDaIK7239skaoKWUAwOjDBUSt0..'
);
# Create new metadata
$metaData = array(
'name' => $_POST['title'],
'shortDescription' => $_POST['shortDescription']
);
# Rename the video file
$file = $_FILES['video'];
rename($file['tmp_name'], '/tmp/' . $file['name']);
$file_location = '/tmp/' . $file['name'];
# Send video to Brightcove
$id = $bc->createVideo($file_location, $metaData);
?>
Thanks in advance for any help!
Er - all you'd need to do is feed the location, not a file handle or anything, no?
$files = $_FILES['video'];
$filename = $files['name'];
$file_location = '/home/username/' . $filename; // maybe append the extension
$id = $bc->createVideo($file_location, $metaData);
Or more simply
$id = $bc->createVideo( '/foo/bar/baz.txt', $metaData );
Looks like you don't need to do anything except point at the file on your local disk. What about:
<?php
# Include & Instantiate
require('../echove.php');
$bc = new Echove(
'z9Jp-c3-KhWc4fqNf1JWz6SkLDlbO0m8UAwOjDBUSt0.',
'z9Jp-c3-KhWdkasdf74kaisaDaIK7239skaoKWUAwOjDBUSt0..'
);
# Create new metadata
$metaData = array(
'name' => $_POST['title'],
'shortDescription' => $_POST['shortDescription']
);
# point at some file already on disk
$file_location = '/path/to/my/file.dat'; // <== if the file is already on the box, just set $file_location with the pathname and bob's yer uncle
# Send video to Brightcove
$id = $bc->createVideo($file_location, $metaData);