简体   繁体   English

如何使用jquery和ajax上传文件?

[英]How to upload file using jquery and ajax?

I am trying to upload a file alone with other form data using AJAX. 我正在尝试使用AJAX单独上传文件以及其他表单数据。 Here I am following this bootstrap and jquery plugin. 在这里,我正在关注这个 bootstrap和jquery插件。

I can figure it out without file uploading, But I want to upload a file with my form. 我可以在不上传文件的情况下弄清楚它,但是我想用表单上传文件。

This is how I tried it: 这是我尝试的方法:

.on('success.form.fv', function(e) {
    // Save the form data via an Ajax request
    e.preventDefault();

    var $form    = $(e.target),
        formData = new FormData(),
        params   = $form.serializeArray(),
        files    = $form.find('[name="new_product_image"]')[0].files,     
        id       = $form.find('[name="product_id"]').val();

    // The url and method might be different in your application
    $.ajax({
        url: './includes/process_edit_products.php',
        method: 'POST',
        //data: $form.serialize()
        data: formData,
        cache: false,
        contentType: false,
        processData: false,
    }).success(function(response) {
        response = jQuery.parseJSON(response);
        // Get the cells
        var $button = $('button[data-id="' + response.product_id + '"]'),
            $tr     = $button.closest('tr'),
            $cells  = $tr.find('td');

        // Update the cell data
        $cells
            .eq(0).html(response.product_name).end()
            .eq(1).html(response.price).end()
            .eq(2).html(response.product_des).end();

        // Hide the dialog
        $form.parents('.bootbox').modal('hide');

        // You can inform the user that the data is updated successfully
        // by highlighting the row or showing a message box
        bootbox.alert('The product is updated successfully.');
    });
});

UPDATE: This is my HTML: 更新:这是我的HTML:

<form id="userForm" method="post" class="form-horizontal" enctype="multipart/form-data" style="display: none;">
    <div class="form-group">
        <label class="control-label" style="width:32%;">ID</label>
        <div class="col-xs-3">
            <input type="text" class="form-control" name="product_id" readonly />
        </div>
    </div>

    <div class="form-group">
        <label class="control-label" style="width:32%;">Product Name:</label>
        <div class="col-xs-5">
            <input type="text" class="form-control" name="product_name" />
        </div>
    </div>

    <div class="form-group">
        <label class="control-label" style="width:32%;">Product Price</label>
        <div class="col-xs-5">
            <input type="text" class="form-control" name="product_price" />
        </div>
    </div>

    <div class="form-group">
        <label class="control-label" style="width:32%;">Product Description</label>
        <div class="col-xs-5">
            <input type="text" class="form-control" name="product_des" />
        </div>
    </div>
        <div class="form-group">
            <label class="control-label" style="width:32%;">New Product Image:</label>
            <div class="col-xs-5">
                <input type="file" size="32" name="new_product_image">
                <p class="help-block">*Only for jpg, gif and PNG files.</p>
            </div>
        </div>  

    <div class="form-group">
            <div class="col-xs-5 col-xs-offset-4">
                <button type="submit" class="btn btn-primary">Update Product</button>
            </div>
    </div>
</form>

Can anybody tell me where I have gone wrong. 谁能告诉我我哪里出问题了。 Any help would be greatly appreciating. 任何帮助将不胜感激。

Thank you. 谢谢。

I think your formData is empty. 我认为您的formData为空。 Try to put these lines before send: 尝试在发送之前放置以下行:

$.each(files, function(i, file) {
  // Prefix the name of uploaded files with "uploadedFiles-"
  // Of course, you can change it to any string
  formData.append('uploadedFiles-' + i, file);
});

$.each(params, function(i, val) {
  formData.append(val.name, val.value);
});

Like they did here http://formvalidation.io/examples/ajax-submit/#using-ajax-to-submit-form-data-including-files 就像他们在这里所做的一样http://formvalidation.io/examples/ajax-submit/#using-ajax-to-submit-form-data-includes-files

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM