代码之家  ›  专栏  ›  技术社区  ›  Nevermore

用Ajax上传jquery文件[重复]

  •  0
  • Nevermore  · 技术社区  · 8 年前
                <div class="form-group">
                    <label class="form-control-label">
                        {{ __('Not Dosyası') }} : <span class="m--font-danger">*</span>
                    </label>
                    <br />
                    <button type="button" onclick="$('#new--file').trigger('click');" class="btn m-btn m-btn--gradient-from-primary m-btn--gradient-to-info">{{ __('Not Dosyasını Yükle') }}</button>
                </div>
                <form id="new--form_file" enctype="multipart/form-data">
                    <input class="m--hide" type="file" name="file" id="new--file" />
                </form><!-- group image form -->
    

    $(function() {
        $("#new--file").on('change', (function(e) {
            LessonNote.new.readURL(this);
        }));
    });
    

    readurl方法:

        readURL: function(input) {
            var file = input.files[0];
            var fileType = file.type;
            var fileSize = file.size;
            var match = ["application/pdf"];
            var maxSize = 20971520; // 20MB
    
            if (fileSize > maxSize) {
                swal(LANGCONVERT.error + '!', LANGCONVERT.file_maximum_size_20, "error");
            } else if (!((fileType === match[0]))) {
                swal(LANGCONVERT.error + '!', LANGCONVERT.file_supported_types_pdf, "error");
            } else {
                $.ajax({
                    url: api.main + api.file_upload,
                    type: 'post',
                    data: file,
                    success:function(data){
                        console.log(data);
                    },
                    cache: false,
                    contentType: false,
                    processData: false
                });
            }
        }
    

    public function store(Request $request) {
        $rules = [
            'file' => 'required|max:10000|mimes:pdf,jp2,jpeg,jpg,png,bmp,tiff,tif,mirax'
        ];
    
        $this->validate($request, $rules);
    
        $data = $request->all();
        $data["file"] = $request->file->store('');
    
        return $this->showMessage($data, 201);
    }
    

    http://localhost:8181/api/file_upload

    1 回复  |  直到 8 年前
        1
  •  2
  •   KroKite    8 年前

    var file = input.files[0];
    ...
    $.ajax({
        ...
        data: file,
        ...
    ...
    

    相反,您需要使用 FormData()

    var file = input.files[0];
    var formData = new FormData();
    formData.append("file", file);
    
    ...
    // and in $.ajax({
    $.ajax({
        ...
         data: formData,
        ...
    ...
    

    Ajax Upload image

    我剪掉了你的其他密码 ...