フロントエンドから画像をアップロードしようとすると、APIからreq.fileが未定義になり続けます。Laravelのguzzle-httpを使用してデータを投稿します。ただし、郵便配達員のフォームデータを使用すると、画像が正常にアップロードされるため、フロントエンドの何かに関係している可能性があると思います。
あなたが私を正しい方向に向けることができれば、それは大いに役立つでしょう。
これが私がこれまでに持っているものです
Nodejsコントローラー
exports.post_image = (req, res, next) => {
console.log(req.file);// outputs undefined
//validate file is present
if (!req.file) return res.status(400).json({message: 'Please upload a image!'});}
ノードjsルート
router.post('/', upload.single('image'), ImageController.post_image);
Laravelコントローラー
public function store(Request $request)
{
$validatedData = Validator::make($request->all(), [
'image' => 'required|image:jpeg,png,jpg|max:2048',
])->validate();
if ($request->hasFile('image')) {
$image = $validatedData['image'];
}
//dd($image);// returns the file and its properties
$url = 'http://localhost:3000/upload';
$response = Http::post($url, [
'image' => $image
]);
dd(json_decode($response));// response is 'Please upload a image!'
$response_decode = json_decode($response);
$message = $response_decode->message;
session()->flash('success', $message);
return redirect()->action('ImageController@index');
}
HTMLページ
<form action="{{ route('image.store') }}" method="POST" enctype="multipart/form-data">
@csrf
@method('PUT')
<div class="form-group">
<label for="image">Image</label>
<input type="file" id="image" name="image" accept="image/png,image/jpeg" class="form-control">
</div>
<div class="form-group">
<button class="btn btn-success">Upload</button>
</div>
</form>
ファイルをマルチパートリクエストとして送信する場合は、リクエストを行う前にattachメソッドを呼び出す必要があります。
特定の行を変更する必要があります、最初の変更、
if ($request->hasFile('image')) {
$image = $request->file('image');
}
次に、次に、
$url = 'http://localhost:3000/upload';
$photo = fopen($image, 'r');
$image_name = 'image' . $image->getClientOriginalExtension();
$response = Http::attach(
'image', $photo, $image_name
)->post($url);
dd($response->json(), $response->status());
HTTPClient(Guzzle HTTPクライアントの周りの表現力豊かで最小限のAPI)を使用する代わりに、GuzzleHTTPクライアントを直接使用できます。
try{
$url = 'http://localhost:3000/upload';
if (!empty($image)){
$guzzleResponse = $client->post($url, [
'multipart' => [
[
'name' => 'image',
'contents' => fopen($image, 'r')
] //,
/** for other parameters
[
'name' => 'description'
'contents' => 'image about cat'
] //put ',' and similarly add other parameters
*/
] // ,
// 'headers' => $headers you can add headers here(commented as you have not added any headers in your code snippet)
]);
if ($guzzleResponse->getStatusCode() == 200) {
$response = json_decode($guzzleResponse->getBody(), true);
}
}
}catch (RequestException $e) {
// you can catch here 400 response errors and 500 response errors
// see this https://stackoverflow.com/questions/25040436/guzzle-handle-400-bad-request/25040600
} catch(Exception $e){
//other errors
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加