javascript - 如何在 Laravel 中通过 jQuery AJAX 发布文件和数据

标签 javascript php jquery ajax laravel-5.2

我在让我的 AJAX 工作时遇到问题。我环顾四周,但似乎找不到任何有助于我构建代码的方法。

现在数据字段输入数据库很好,但是我还想添加文件上传(个人资料图片),但是当我查看网络选项卡时,它不会出现在表单数据中。目前我并不太担心 Controller 本身,但是如何获取 AJAX 请求以将文件发送到 Controller ?

如果有人知道我该如何解决这个问题,我将不胜感激。

谢谢!

AccountController.php

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\User;
use App\Http\Requests;
use Illuminate\Support\Facades\Auth;
class AccountController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        //
        return view('Account.index');
    }
    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function create()
    {
        //
    }
    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request)
    {
        //
    }
    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }
    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }
    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request)
    {
        $this->validate($request, [
            'name' => '',
            'email' => '',
            'telephone' => '',
            'job_title' => '',
            'profile_description' => '',
            'education' => '',
        ]);
        User::find(Auth::user()->id)->update([
            'name' => $request->get('name'),
            'email' => $request->get('email'),
            'telephone' => $request->get('telephone'),
            'job_title' => $request->get('job_title'),
            'profile_picture' => $request->get('profile_picture'),
            'profile_description' => $request->get('profile_description'),
            'education' => $request->get('education'),
        ]);
        $userImage = User::find(Auth::user()->id);
        if (!empty($request->file('profile_picture')) && $request->file('profile_picture')->isValid()) {
            $fileName = md5(time() . pathinfo($request->file('profile_picture')->getClientOriginalName(), PATHINFO_FILENAME)) . '.' . pathinfo($request->file('profile_picture')->getClientOriginalName(), PATHINFO_EXTENSION);
            $request->file('profile_picture')->move('profile-pictures', $fileName);
            $userImage->update([
                'profile_picture' => $fileName,
            ]);
        } else {
            $fileName = $request->get('old-image');
        }
        $userImage->update([
            'profile_picture' => $fileName,
        ]);
    }

形式
<form class="form-horizontal" id="account-update" role="form" method="POST" action="{{ url('account.update', auth()->user()->id) }}" enctype="multipart/form-data">
  {{ csrf_field() }}
  <div class="form-group">
    <label for="name" class="col-sm-2 control-label">Name</label>

    <div class="col-sm-10">
      <input name="name" type="text" class="form-control" id="name" placeholder="Name">
    </div>
  </div>
  <div class="form-group">
    <label for="email" class="col-sm-2 control-label">Email</label>

    <div class="col-sm-10">
      <input name="email" type="email" class="form-control" id="email" placeholder="Email">
    </div>
  </div>

  <div class="form-group">
    <label for="telephone" class="col-sm-2 control-label">Contact Number</label>

    <div class="col-sm-10">
      <input name="telephone" type="telephone" class="form-control" id="telephone" placeholder="+(44)754 5635 950">
    </div>
  </div>

  <div class="form-group">
    <label for="job_title" class="col-sm-2 control-label">Job Description</label>

    <div class="col-sm-10">
      <input name="job_title" type="text" class="form-control" id="job_title" placeholder="Web Developer">
    </div>
  </div>

  <div class="form-group">
    <label for="profile_description" class="col-sm-2 control-label">About Me</label>

    <div class="col-sm-10">
      <textarea name="profile_description" class="form-control" id="profile_description" placeholder="Tell us about yourself..."></textarea>
    </div>
  </div>

  <div class="form-group">
    <label for="education" class="col-sm-2 control-label">Education</label>

    <div class="col-sm-10">
      <input name="education" type="text" class="form-control" id="education">
    </div>
  </div>

  <div class="form-group">
    <label for="profile_picture" class="col-sm-2 control-label">Profile Picture</label>

    <div class="col-sm-10">
      <input name="profile_picture" type="file" class="form-control" id="profile_picture">
    </div>
  </div>

  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn send-btn">Submit</button>
    </div>
  </div>
</form>

AJAX
<script>
$(document).ready(function(){
  $('#account-update').on('submit', function(e) {
    e.preventDefault();

    $.ajax({
      url: '{{ route('account.update', auth()->user()->id) }}',
      enctype: 'multipart/form-data',
      method: "PUT",
      data: {
        'name':$('input[name=name]').val(),
        'email':$('input[name=email]').val(),
        'telephone':$('input[name=telephone]').val(),
        'job_title':$('input[name=job_title]').val(),
        'profile_description':$('textarea[name=profile_description]').val(),
        'education':$('input[name=education]').val(),
        'profile_picture': $('file[name=profile_picture]').val(),
        '_token': $('input[name=_token]').val()
      },
      success: function(data){
        console.log(data);
      }
    });
    return false;
  });
});
</script>

最佳答案

试试 FormData .

The FormData object lets you compile a set of key/value pairs to send using XMLHttpRequest. It is primarily intended for use in sending form data, but can be used independently from forms in order to transmit keyed data. The transmitted data is in the same format that the form's submit() method would use to send the data if the form's encoding type were set to multipart/form-data.


$('#account-update').on('submit', function(e) {
    e.preventDefault();
    var formData = new FormData();

    // other inputs
    formData.append("userfile", $('file[name=profile_picture]').files[0]);

    //append some non-form data also
    formData.append('name',$('input[name=name]').val()),
    $.ajax({
        type: "POST",
        url: postDataUrl,
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function(data, textStatus, jqXHR) {
           //process data
        },
        error: function(data, textStatus, jqXHR) {
           //process error msg
        },
});

关于javascript - 如何在 Laravel 中通过 jQuery AJAX 发布文件和数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39076222/

相关文章:

javascript - 如果 slider 从头开始,Coda-Slider 不应滑过所有元素

php - SimpleXmlElement 未能获取项目

php - MySQL将查询限制为一个一致的值

javascript - 在 then 函数中调用 Jquery ajax

javascript - 动态加载时,jQuery获取调用&lt;script&gt;标记

javascript - 为什么Javascript中的保留关键字不能用作变量名?

javascript - 如何使用 jQuery 查询字符串?

javascript - 如何处理ASP .NET Api HTTPResponseMessage以下载文件

php - 为什么我的常量整数类型转换为字符串?

javascript - 如何在一页中将JavaScript与具有相同ID的重复元素一起使用?