Search code examples
laravelimageform-data

Controller is getting one image for both names


i'm sending the image with form data one image for student marksheet and one image for it's profile picture. but when i see the response in headers it showing one image for both the parameters.

HTML Code for marksheet

<div class="col-md-3 offset-1">
  <input class="form-control" type="file" name="tei" class="tei">
  <label class="control-label">Image</label><i class="bar"></i>
</div>

HTML Code for profile picture

<div class="col-md-3 offset-1">
  <input class="form-control" type="file" name="image" >
  <label class="control-label">Image</label><i class="bar"></i>
</div>

Jquery code for send image to controller

formdata.append('image',$('input[type=file]')[0].files[0]);
formdata.append('tei',$("input[name='tei']")[0].files[0]);

Controller Code

public function studentform(Request $request)
{
    dd($request->all());
}

Header Response

Here image is use for profile picture and tei for marksheet (now look both the names are getting same image name)

image" => UploadedFile {#264
    -test: false
    -originalName: "Capture.JPG"
    -mimeType: "image/jpeg"
    -error: 0
"tei" => UploadedFile {#265
    -test: false
    -originalName: "Capture.JPG"
    -mimeType: "image/jpeg"
    -error: 0
    #hashName: null

Solution

  • In your Javascript code you are appending one image with the input type and the other with the input name, Try appending both with the input name.

    Depending on your HTML structure (e.g. which element comes first), it will select the wrong image.

    Try this:

    formdata.append('image', $("input[name='image']")[0].files[0]);  
    formdata.append('tei', $("input[name='tei']")[0].files[0]);