Laravel使用Ajax上传文件

Lih*_*hai 2 php ajax jquery file-upload laravel

我正在使用Laravel框架.我有一种向数据库添加新项目的形式,用户也可以拖放文件.然后,显示进度条直到完成,使用Ajax将文件上载到服务器.

提交该表单后,我addItem在控制器中运行该函数,我想做/检查:

  1. 该文件已托管在服务器中(成功上载)
  2. 如果文件托管在服务器中,我该如何找到它?(我给它一个随机的名字)
  3. 如果用户选择不提交表单,我希望从服务器中删除该文件,因此我不会将文件连接到我的数据库中的任何项目

您能否就如何完成这些任务提出任何建议?

Sna*_*rak 6

要通过AJAX发送文件,您需要使用FormData哪一类XMLHttpRequest2,它不适用于IE <10.

您还需要AJAX2来显示进度.

样本通过AJAX提交文件和进度表格:

我在这里做了一个例子.在此示例中,表单使用AJAX通过AJAX发送数据和文件,FormData并在#progress使用progress事件时显示上载进度百分比.显然它是一个样本,可以改变以适应它.

$('form').submit(function(e) { // capture submit
    e.preventDefault();
    var fd = new FormData(this); // XXX: Neex AJAX2

    // You could show a loading image for example...

    $.ajax({
      url: $(this).attr('action'),
      xhr: function() { // custom xhr (is the best)

           var xhr = new XMLHttpRequest();
           var total = 0;

           // Get the total size of files
           $.each(document.getElementById('files').files, function(i, file) {
                  total += file.size;
           });

           // Called when upload progress changes. xhr2
           xhr.upload.addEventListener("progress", function(evt) {
                  // show progress like example
                  var loaded = (evt.loaded / total).toFixed(2)*100; // percent

                  $('#progress').text('Uploading... ' + loaded + '%' );
           }, false);

           return xhr;
      },
      type: 'post',
      processData: false,
      contentType: false,
      data: fd,
      success: function(data) {
           // do something...
           alert('uploaded');
      }
    });
});
Run Code Online (Sandbox Code Playgroud)

看看如何运作!!:http://jsfiddle.net/0xnqy7du/3/

拉瓦尔:

laravel您可以获取文件Input::file,移动到另一个位置并在需要时保存在数据库中:

Input::file('photo')->move($destinationPath, $fileName);

// Sample save in the database
$image = new Image();
$image->path = $destinationPath . $fileName;
$image->name = 'Webpage logo';
$image->save();
Run Code Online (Sandbox Code Playgroud)