我正在尝试使用last.fm创建一个节点。
$field = content_fields('field_my_image',"events"); //to get field
$validators = array_merge(filefield_widget_upload_validators($field), imagefield_widget_upload_validators($field)); //image validator
$files_path = filefield_widget_file_path($field); //save path
$src_path=$data->image[3]; // img url from last.fm eg: http://userserve-ak.last.fm/serve/252/502025.jpg
$file = field_file_save_file($src_path, $validators, $files_path, FILE_EXISTS_REPLACE);//save file
$nodenew->field_my_image = array(
array(
'fid' => $file['fid'],
'title' => $file['filename'],
'filename' => $file['filename'],
'filepath' => $file['filepath'],
'filesize' => $file['filesize'],
'filemime' => $file['filemime'],
),
);//insert file details to node
现在节点已创建,但没有图像并且收到消息'所选文件502025.jpg无法保存。该文件不是已知的图像格式。'
答案 0 :(得分:7)
Drupal 7为您正在做的大部分工作提供了一个函数:system_retrieve_file()。
应该有一个文件模块功能,用于根据URL将文件保存到Drupal,但至少该功能确实存在......只是不在任何人看的地方。您可以使用system_retrieve_file()和第三个参数TRUE来创建托管文件(调用file_save_data())。
用法,一个比Jav_Rock更简单的例子,但基本相同,只是跳过散列路径的幻想:
$url = 'http://example.com/picture.png';
$directory = file_build_uri('custom_directory');
if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY)) {
// If our directory doesn't exist and can't be created, use the default.
$directory = NULL;
}
$file = system_retrieve_file($url, $directory, TRUE);
答案 1 :(得分:2)
找到了解决方案。
我们首先需要通过在节点创建功能中调用MODULENAME_save_image_local($ url)将图像保存到drupal文件夹:
$src_path = MODULENAME_save_image_local($url);
添加此功能:
function MODULENAME_save_image_local($url) {
$hash = md5($url);
$dir = file_create_path('lastfm');
if (!file_check_directory($dir)) {
mkdir($dir, 0775, FALSE);
}
$hash = md5($url);
$cachepath = file_create_path('CUSTOMFOLDERNAME/'. $hash.'.jpg');
if (!is_file($cachepath)) {
$result = eventpig_lastfm_fetch($url, $cachepath);
if (!$result) {
//we couldn't get the file
return drupal_not_found();
}
}
return file_directory_path() .'/CUSTOMFOLDERNAME/'. $hash.'.jpg';
}
/**
* Api function to fetch a url and save image locally
*/
function MODULENAME_fetch($url, $cachepath) {
if (!$url) {
return drupal_not_found();
}
$result = drupal_http_request($url);
$code = floor($result->code / 100) * 100;
$types = array('image/jpeg', 'image/png', 'image/gif');
if ($result->data && $code != 400 && $code != 500 && in_array($result->Content-Type, $types)) {
$src = file_save_data($result->data, $cachepath);
}
else {
return drupal_not_found();
}
return TRUE;
}
答案 2 :(得分:1)