1. 微信小程序上傳圖片
wx.uploadFile
使用及詳情請看官方文檔
舉個例子:
uploadFile: function () {
wx.uploadFile({
url: _global.domain + '/article/file/upload',
filePath: this.imageFiles[0],
name: 'file',
formData:{
'user': 'test'
},
success: function(res){
console.log('Test upload image file.')
console.log(res)
}
})
}
此處是舉個例子將我本地的imageFiles數組中的第一個上傳到了圖中所示的url中。
2. 接收文件
這里就需要獲取到文件并且解析它,將其移入到/site/file文件目錄并且存入到數據庫中。
if ($_FILES['file']) {
$uri = file_unmanaged_copy($_FILES["file"]["tmp_name"], "public://2018-07/" . $_FILES["file"]["name"], FILE_EXISTS_RENAME);
$createdFile = File::create([
'uri' => $uri
]);
$createdFile -> save();
}
解釋一下是什么意思:
PHP接受到的文件會將其存入到臨時文件當中,根據$_FILES['file']['tmp_name'] 獲取。
file_unmanaged_copy 該方法有三個參數,第一個參數是待移動文件的位置,第二個參數是移動的位置及文件名,第三個參數則是如果文件重名,會在其后綴加上數字0,如果加上0也重名,則會在后面加上數字1。直到文件名不重復為止。
之后調用File->save() 存入數據庫
3. 創(chuàng)建Content,并且引入已上傳的圖片
太過簡單直接上代碼
$file = File::load($createdFile->id());
$node = Node::create([
'uid' => '1941562',
'type' => 'bulletin',
'title' => 'Test node',
'body' => 'aaaaaaaaaaaaaaaaaaaaaaaa',
'status' => 1,
'promote' => 0,
'sticky' => 0,
'langcode' => LanguageInterface::LANGCODE_NOT_SPECIFIED,
'created' => REQUEST_TIME,
'changed' => REQUEST_TIME,
'field_bulletin_image' => array($file,$file)
]);
$node->save();
這部分代碼緊接著上一部分代碼。
注:bulletin是node的機器碼。field_bulletin_image也是,是該node的field的機器碼。
這段代碼作用就是創(chuàng)建一個node,將文章內容與視頻圖片綁定起來。