2016-08-02 98 views
0

为什么即使文件上传成功,我上传的文件没有反映出请求?laravel + dropzone文件无法上传

HTML

<div id="upload_excel" class="dropzone form-control"> 

    <div class="fallback"> 
     <input name="file" type="file" multiple /> 
    </div> 

</div> 

JS

var baseUrl = "{{ url('/') }}"; 
var token = "{{ Session::getToken() }}"; 

Dropzone.autoDiscover = false; 

var myDropzone = new Dropzone("#upload_excel", { 
    paramName: "file", 
    acceptedFiles: ".xls,.xlsx", 
    maxFiles: 1, 
    maxFilesize: 10, 
    url: baseUrl + "/upload", 
    params: { 
     _token: token 
    } 
}); 

控制器

class UploadsController extends Controller 
{ 
    public function upload(Request $request) { 
     return $file = $request->all(); 
    } 
} 

请求预览 [enter image description here 请求响应

{"_token":"ePssa9sPZxTcRR0Q4Q8EwWKjODXQ8YpCcH8H9wRP","upload_date":"2016-08-02","file":{}} 

我错过了什么还是什么?

+0

那么你实际上并没有在你的后端做任何事情。它可能只是无法解析为一个resposne? –

+0

嗯。所以我可以上传一个文件(特别是excel文件)从dropzone到数据库的正确方式是什么? – Jefsama

+0

响应标签里有什么? – Chris

回答

1

我有这样

public function upload(Request $request) { 
    // validation etc 
    // ... 

    // I have a table and therefore model to list all excels 
    $excelfile = ExcelFile::fromForm($request->file('file')); 

    // return whater ... 
} 

在我ExcelFile型号

protected $baseDir = 'uploads/excels'; 

public static function fromForm(UploadedFile $file) { 
    $excelfile = new static; 

    $name = time() . $file->getClientOriginalName(); 
    $name = preg_replace('/\s+/', '', $name); 
    $excelfile->path = $excelfile->baseDir . '/' . $name; 

    $file->move($excelfile->baseDir, $name); 

    return $excelfile; 
} 

您还需要添加UploadedFile的模型中的

use symfony\Component\HttpFoundation\File\UploadedFile; 

我的悬浮窗就像是定义一个控制器这确保了正确的令牌处理

<form action="https://stackoverflow.com/users/{{ $id }}/media/excelupload" id="drop-zone" class="dz dropzone"> 
    {{ csrf_field() }} 
</form> 

<script> 

    new Dropzone("#drop-zone", { 
     maxFilesize: 3, // MB 
     maxFiles: 10, 
     dictDefaultMessage: "Upload Excel.", 
     init: function() { 
      var known = false; 
      this.on("success", function(file, responseText) { 
       // do stuff 
      }); 
      this.on('error', function() { 
       // aler stuff 
      }); 
      this.on("addedfile", function() { 
       if (this.files[10]!=null){ 
        this.removeFile(this.files[0]); 
        if (known === false) { 
         alert('Max. 10 Uploads!') 
         known = true; 
        } 
       } 
      }); 
     } 
    }); 
</script> 

我希望这有助于

+0

我按照你的例子,得到这个错误:'类型错误:参数1传递给应用程序\ ExcelFile :: fromForm()必须是应用程序\ UploadedFile,实例Illuminate \ Http \ UploadedFile' – Jefsama

+0

您需要添加“使用symfony的\分量\ HttpFoundation \文件\ UploadedFile的;”在最上面(编辑:粘贴错误的代码片段)我会在第二个更新答案 –

+0

它的工作原理!非常感谢! :) – Jefsama