【问题标题】:Can't upload a file to Laravel with jQuery .post method [duplicate]无法使用 jQuery .post 方法将文件上传到 Laravel [重复]
【发布时间】:2018-03-25 11:15:55
【问题描述】:

这是我的html

<input type="file" class="form-control" name="file-name" id="file-id">

这里是应该向 api 发送文件的 JS

var file = $('input#file-id').val();
$.post('my/url/that/works', {
    file: file,
    volume: volume
}).done(function () {
    //something
}).fail(function () {
    //something else
});

最后是我在 Laravel 中的方法:

public function ajaxMethod(Request $request)
{
    if ($request->hasFile('file')) {
        echo "it does";
    }else{
        echo "it does not"; //     <- that happens
    }
    var_dump($request->getContent());//vardumps ('C:/fakepath/[correct_filename])
}

ajax 调用说它没有文件。我认为我只上传文件名,而不是文件。怎么改?

【问题讨论】:

  • 确实,你不能使用 jQuery post 函数上传文件。
  • 好的,所以我需要使用 .ajax 函数?
  • 在请求中发送文件时,您需要将它们编码为二进制数据,而不是序列化它们。为此,请使用 FormData 对象。请参阅我标记的副本以获取更多信息

标签: javascript php jquery ajax laravel


【解决方案1】:

使用这个来获取文件:

var file = $('input#file-id').prop('files')[0];

代替您的代码:var file = $('input#file-id').val();

【讨论】:

  • 这是一半的答案。更大的问题是缺乏二进制数据。
  • 是的,我看到了你对 $.post 的评论
  • $request->file('image')->store('images');
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-03
  • 2016-09-14
  • 2016-06-06
  • 2011-02-05
  • 2019-12-01
  • 2020-01-01
  • 1970-01-01
相关资源
最近更新 更多