1

I am trying to upload a form which contains files through ajax, but then on the server side I just get a plain text that I can't use.

if I use processData: false, contentType: false and cache: false, this happens, and if I don't use them the file wouldn't upload.

JavaScript:

$("#purchase-attachment-form").on('submit', function (e) {
    if ($('#paf_input').get(0).files.length === 0) {
        alert('Please Select A file');
        return;
    }
    e.preventDefault();
    $.ajax({
        url: "{{route('add_attachment_to_purchase')}}",
        data: new FormData($("#purchase-attachment-form")[0]),
        type: 'post',
        processData: false,
        cache: false,
        success: function (data) {
            alerts(data, 'Adding Purchase Attachment');
        },
        error: function (jqXHR, textStatus, errorThrown) {
            alerts(2, "Adding Purchase Attachment");
        }
    });
});

Html:

<form id="purchase-attachment-form" class="modal-content">
    <div class="modal-header">
        <h4 class="modal-title" id="defaultModalLabel">Add Attachment</h4>
    </div>
    <div class="modal-body">
        <div class="row clearfix">
            <div class="col-lg-6">
                <div class="form-group">
                    <label>Type</label>
                    <div class="form-line">
                        <select class="form-control select" name="type">
                            <option value="quotation">Quotation</option>
                            <option value="conparison">Comparison</option>
                            <option value="invoice">Invoice</option>
                            <option value="payment_offer">Payment Offer</option>
                        </select>
                        <input type="hidden" name="purchase" id="purchase_on_attachment" value="{{encrypt($purchase->id)}}"class="form-control" />
                    </div>
                </div>
            </div>
            @csrf
            <div class="col-lg-6">
                <div class="form-group">
                    <input type="file" class="hidden" id="paf_input" name="attachment" required />
                    <button type="button"  id="paf_btn" onclick="$('#paf_input').trigger('click');" class="material-icons waves-effect btn btn-circle">add</button>
                </div>
            </div>
        </div>
    </div>
    <div class="modal-footer">
        <button type="submit" class="btn btn-primary waves-effect">Add</button>
        <button type="button" class="btn btn-default waves-effect" data-dismiss="modal">CLOSE</button>
    </div>
</form>

Controller:

public function create(Request $request) {
//        return $request->all();
//        return $request->getContent();
        $this->validate($request, [
            'type' => 'required',
            'purchase' => 'required',
            'attachment' => 'required',
        ]);
        $role = \App\Role::where('role', strtoupper(auth()->getDefaultDriver()))->first();
        if ($role == null) {
            return '2';
        }
        $role_id = $role->id;
        $time = time();
        if ($request->hasFile('attachment')) {
            $attachment = $request->file('attachment');
            $att_file_name = $attachment->getClientOriginalName();
            $att_file = ($time++) . $att_file_name;
            $att_file_saved = $request->attachment->storeAs('public/purchase/attachments/', $att_file);
        }
        $pa = new Purchase_Attachment();
        $pa->type = $request->type;
        $pa->purcahse_id = decrypt($request->purcahse);
        $pa->user_id = auth()->user()->id;
        $pa->role_id = $role_id;
        $pa->address = $att_file;
        $pa->save();
        return redirect(route('view_purchase_view', ['prid' => $request->purcahse]));
    }

I can't get any data by specifying the name of the input on the server-side. The Data on the server-side by returning $request->getContent():

------WebKitFormBoundaryhtJyrJXT3BFCCQHF
Content-Disposition: form-data; name="type"

quotation
------WebKitFormBoundaryhtJyrJXT3BFCCQHF
Content-Disposition: form-data; name="purchase"

eyJpdiI6IktVUHh4ZmE1d3VGa3lhV0JZUDdtRkE9PSIsInZhbHVlIjoiRDQ3Zmt6N2VwODhpamN6VVpGUHhCdz09IiwibWFjIjoiNWE3ZTViOTgwOGQxNmI3MGU1ZTdmZTE3MDZmN2FhZTYxYTMzNzY1NjA3NzliMDQwNjJlY2QzNDg3OGVjMDk4ZSJ9
------WebKitFormBoundaryhtJyrJXT3BFCCQHF
Content-Disposition: form-data; name="_token"

YMTaQStR84KBEXuocHKoiDj6dqlpzdUju9MUAbtq
------WebKitFormBoundaryhtJyrJXT3BFCCQHF
Content-Disposition: form-data; name="attachment"; filename="safe_image.jpg"
Content-Type: image/jpeg

Some Binary Data Here, Stakoverflow denied uploading
BSK
  • 47
  • 1
  • 9

1 Answers1

0

Have you tried to create a variable like:

let x = new FormData();
x.append("name_file", data);

And in ajax call

 {
    ...
        data: x,
        processData: false,
        contentType: false,
         type: 'POST',

    ...
    }

and in backend, in your Controller :

public myFunction(Request $request){
 $file = $request->file("name_file");
}

In this post you cand find one example how you should send data with JQuery:

How to send FormData objects with Ajax-requests in jQuery?

LorenzoBerti
  • 6,704
  • 8
  • 47
  • 89
  • Yeah, I have tried that too, but still returns validation error. – BSK Jul 23 '19 at 10:14
  • let x = new FormData(); x.append('type', $("#pa-type").val()); x.append('purchase', $("#pa-purchase").val()); x.append('attachment', $("#paf_input")[0].files[0]); $.ajax({ url: "{{route('add_attachment_to_purchase')}}", data: x,//new FormData($("#purchase-attachment-form")[0]), type: 'post', – BSK Jul 23 '19 at 10:14
  • {"message":"The given data was invalid.","errors":{"type":["The type field is required."],"purchase":["The purchase field is required."],"attachment":["The attachment field is required."]}} – BSK Jul 23 '19 at 10:15
  • contentType : false, is important see also: https://stackoverflow.com/questions/44354370/how-to-read-formdata-object-in-laravel – LorenzoBerti Jul 23 '19 at 12:37
  • Even using contentType: false, it is the same. – BSK Jul 24 '19 at 04:27
  • Can you post your controller? – LorenzoBerti Jul 24 '19 at 11:07
  • Yeah, Here it is: – BSK Jul 28 '19 at 04:07