HTML5,File API和jQuery发布图片 [英] HTML5, File API and jQuery posting image

查看:137
本文介绍了HTML5,File API和jQuery发布图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,我在对话框中显示,它有一个提交按钮,单击时使用jQuery使用AJAX将表单发布到服务器。这是一个MVC动作方法。上传的文件始终为null。在使用谷歌时,我读到你通常不能使用AJAX发布文件,除非你使用某种插件。

I have a form that I show in a dialog, and it has a "submit" button that when clicked uses jQuery to post the form to the server using AJAX. This is to an MVC action method. The uploaded file was always null. Upon using Google, I read that you cannot normally post files using AJAX unless you use some sort of plugin.

我不想使用插件而我读到这个可以使用支持HTML5文件API的浏览器来完成,所以我想让它使用它。

I did not wish to use a plugin and I read that this could be done with browsers that support the HTML5 File API, so I would like to get it working with this.

我不关心拖放或其他什么那一刻,我只想使用jQuery将文件与表单的其余部分一起发布。

I do not care about drag and drop or anything else at the moment, I only want to post up the file along with the rest of the form using jQuery.

到目前为止,我有:

这是表格的部分视图:

@model ImageReceiptLineModel

@using (Html.BeginForm(MVC.EditImageReceiptLine(), FormMethod.Post, new { enctype = "multipart/form-data" }))
{
  @Html.HiddenFor(model => model.ReceiptLineSetID)
  @Html.HiddenFor(model => model.LineNumber)
  <input id="uploadFile" name="uploadFile" type="file" value="Choose New Image" />
  @Html.LabelFor(model => model.ImageDescription)
  @Html.TextBoxFor(model => model.ImageDescription)
}

这是发送表格的jQuery

This is the jQuery for the sending of the form

if ($Form.valid()) {
        // get the url and the form data to send the request
        var Url = $Form.attr('action');
        var FormData = $Form.serialize();

        // now do the ajax call
        $.ajax({
            url: Url,
            data: FormData,
            type: 'POST',
            cache: 'false',
            success: function (data, textStatus, jqXHR) {
                // do something here
            },
            error: function (jqXHR, textStatus, errorThrown) {
                // do something here
            }
        });
    }

这是MVC操作方法:

/// <summary>
/// Edit receipt line action
/// </summary>
/// <returns>Action result</returns>
[HttpPost]
public virtual ActionResult EditImageReceiptLine(HttpPostedFileBase uploadFile, ImageReceiptLineModel model)
{

}

我需要添加什么才能将文件添加到表单中? FormData是我发布到服务器的序列化表单数据。

What do I need to add to this to add the file to the form? "FormData" is the serialised form data that I post to the server.

推荐答案

这是一个 指南 关于文件API可用于上传文件。但是不要忘记这对IE9不起作用。如果您需要支持此类浏览器,可以使用隐藏的iframe来模拟使用AJAX上传文件。这就是为什么存在 jquery.form 等插件的原因。为了使它成为一行代码,您不必担心浏览器支持和东西:

Here's a guide about the File API that could be used to upload files. But don't forget that this won't work on IE9. If you need to support such browsers you could use hidden iframes to simulate uploading files with AJAX. That's why plugins such as jquery.form exist. In order to make it a single line of code so that you don't have to worry about browser support and stuff:

if ($Form.valid()) {
    // get the url and the form data to send the request
    $Form.ajaxSubmit({
        success: function (data, textStatus, jqXHR) {
            // do something here
        },
        error: function (jqXHR, textStatus, errorThrown) {
            // do something here
        }
    });
}






更新:


UPDATE:

根据评论部分的要求,您可以使用File API。

As requested in the comments section here's how you could use the File API.

我们假设您有以下表格:

Let's suppose that you have the following form:

@using (Html.BeginForm(MVC.EditImageReceiptLine(), null, FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.HiddenFor(model => model.ReceiptLineSetID)
    @Html.HiddenFor(model => model.LineNumber)
    <input id="uploadFile" name="uploadFile" type="file" value="Choose New Image" />
    @Html.LabelFor(model => model.ImageDescription)
    @Html.TextBoxFor(model => model.ImageDescription)    
}

以及一些会触发表单提交的链接:

and some link that will trigger the form submission:

<a href="#" id="upload">Upload the file using HTML5 File API</a>

现在在js文件中你可以拥有以下内容:

Now in a js file you could have the following:

$('#upload').click(function () {
    if (!window.FileReader) {
        // the browser doesn't support the File API - there's no need
        // to continue;
        alert('To use this functionality please use a modern browser');
        return;
    }

    var $form = $('form');
    var uri = $form.action;
    var xhr = new XMLHttpRequest();
    var fd = new FormData();

    $form.find(':input').each(function () {
        if ($(this).is('input[type="file"]')) {
            var files = $(this)[0].files;
            if (files.length > 0) {
                fd.append(this.name, files[0]);
            }
        } else {
            fd.append(this.name, $(this).val());
        }
    });

    xhr.open('POST', uri, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            // handle response.
            alert(xhr.responseText); 
        }
    };

    xhr.send(fd);
});

这篇关于HTML5,File API和jQuery发布图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆