Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
233 views
in Technique[技术] by (71.8m points)

php - Laravel $request->file() returns null

having trouble trying to upload files using Laravel on the back-end.

Issue

Laravel $request->file() method returns null.

Setup

I build up an AJAX request using superagent, debugged the request and everything seems fine. The Content-Length changes depending on the image I add, indicating an image has been added to the request. The Content-Type is also set to multipart/form-data.

// request headers
Content-Length:978599
Content-Type:multipart/form-data; 

// request payload
Content-Disposition: form-data; name="files"; filename="item-keymoment.png"
Content-Type: image/png

But I'm unable to get the file in Laravel. Using $request->file('files') returns NULL, but if I debug the $_FILES array, I noticed that a my file has been uploaded.

dd($request->file('files'))
// NULL

dd($_FILES);
// array:1 [
//   "files" => array:5 [
//     "name" => "item-keymoment.png"
//     "type" => "image/png"
//     "tmp_name" => "/tmp/phpipbeeM"
//     "error" => 0
//     "size" => 978274
//   ]
// ]

dd($request->files->all())
// []

What might be causing Laravel to ignore the file?
Content-Type of the input file not being application/octet-stream?

Below have answered the question.

question from:https://stackoverflow.com/questions/38226875/laravel-request-file-returns-null

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You should add to the form tag enctype="multipart/form-data"

For example:

<form method="POST" action="{{route('back.post.new')}}" enctype="multipart/form-data">
.............
</form>

Adding it you can use your custom Request.

I hope this can you help!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...