答案 0 :(得分:2)
当提供要作为字符串上传到Guzzle
客户端的内容时,
Guzzle
尝试推断有关文件的必要信息,例如filename,content-type。
通过在分段有效负载中传递有关文件名和内容类型的信息,您可以帮助Guzzle
正确推断这些信息以构建分段请求。
[
//...
'multipart' => [
[
'name' => 'fileName',
'contents' => $request->file('file')->get(),
'filename' => $request->file('file')->getName(),
'headers' => [
'content-type' => $request->file('file')->getMimeType(),
]
]
]
]
答案 1 :(得分:2)
要使此功能正常运行,您需要进行一些修改(在我的终端上进行了测试):
要获取文件的内容,您需要$request->file('file')
,然后在其上使用file_get_contents()
。您可能会失去get()
部分。
确保您也发送了标头以接受multipart/form-data
:
"Accept" => "multipart/form-data"
表单中的字段name
和filename
是两回事。前者是字段的名称,而后者是文件的名称。您需要同时发送。
尝试一下:
protected function uploadFile(Request $request){
$file = $request->file('file');
$body = [
"headers" => [
"Accept" => "multipart/form-data",
"Authorization" => "Bearer {$this->token}"
],
"multipart" => [
"name" => "file",
"contents" => file_get_contents($file),
"filename" => $file->getClientOriginalName()
]
];
return (new Client)->request('POST', 'https://.sharepoint.com/...', $body);
}
P.S。 -您可以使用isValid()
检查文件是否有效:
if ($request->file('file')->isValid()) {
//
}
有关以下内容的官方文档:https://laravel.com/docs/7.x/requests#retrieving-uploaded-files
答案 2 :(得分:1)
将内容类型添加为blob。
axios.post(
'https://sharepoint....'
,data.get('file')
{
'headers' {
'Authorization': `Bearer ${this.token}`
,'Content-Type': 'blob',
}
}
)
答案 3 :(得分:0)
尝试类似这样的方法。
从您的->get()
$request->file()
//Get the file object from the request.
$file = $request->file('file');
//Make the request
return (new Client)->request('POST', 'https://.sharepoint.com/sites....', [
'headers' => [ 'Authorization' => "Bearer {$this->token}" ],
'multipart' => [
[
'name' => 'FileContents',
'contents' => $file,
'filename' => $file->getClientOriginalName()
],
],
]);
答案 4 :(得分:0)
我认为,您应该先将其临时存储在本地服务器中的某个位置,然后再将该文件发送到sharepoint,删除该临时文件,我认为如果立即发送而不存储它,该文件将被破坏。请尝试以下方式
$file = $request->file('logo');
$original_name = $file->getClientOriginalName(); // get original file
$name = time() . '_' . $original_name; // store it in different name so it would not be duplicated
$path = base_path() .'/public_html/your_project/public/temporary/'; // full path of file folder
// store the uploaded file
$file->move($path, $name);
$body = [
"headers" => [
"Authorization" => "Bearer {$this->token}"
],
"multipart" => [
"name" => "logo",
"contents" => fopen($path . $name, 'r')
]
];
$response = (new Client)->request('POST', 'https://.sharepoint.com/...', $body);
// remove the file after done
unlink($path . $name);
return $response;
希望这对您有用!如果我错了请纠正我