选择图像后立即使用不同的图像按钮进行移动上传?

时间:2014-03-11 14:14:48

标签: css file-io upload

我想使用我自己的.png图片来触发

<input type="file" id="pictureCapture" accept="image/*; capture=camera" />

然后立即将图像上传到MVC控制器。

那么,第一个问题是如何用可点击的图像替换输入标签?

第二,到目前为止,我只看到文件上传为两部分过程。单击“浏览”按钮,选择文件,然后单击“上载”以发送文件。

如何整合它以便在您选择文件后立即上传?

是否有第三方控件为我做这一切?

1 个答案:

答案 0 :(得分:0)

这是我最终做的事情:

HTML:

<input type="file" id="pictureCapture" accept="image/*; capture=camera" style="visibility:hidden;" />

<a href="#" id="uploadPhotoFromCamera"><img src="@(Url.Content("~/Images/Mobile/Camera.png"))" /></a>

使用Javascript:

<script>
    $("#uploadPhotoFromCamera").click(function (e) {
        e.preventDefault();

        $("#pictureCapture").trigger("click");
    });

    $('#pictureCapture').on("change", function () {
        var formdata = new FormData(); //FormData object

        var fileInput = document.getElementById('pictureCapture');

        //Iterating through each files selected in fileInput
        for (i = 0; i < fileInput.files.length; i++) {
            //Appending each file to FormData object
            formdata.append(fileInput.files[i].name, fileInput.files[i]);
        }

        //Creating an XMLHttpRequest and sending
        var xhr = new XMLHttpRequest();
        xhr.open('POST', '@(Url.Action("UploadMobile", "Document"))')
        xhr.send(formdata);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4 && xhr.status == 200) {
                alert('success');
            }               
        }

        return false;
    });
</script>

控制器:

public virtual ActionResult UploadMobile()
{
    List<HttpPostedFileBase> files = new List<HttpPostedFileBase>();
    for (int i = 0; i < Request.Files.Count; i++)
    {
        files.Add(Request.Files[i]); //Uploaded file
    }

    // Do whatever now with your list of files

    return Json("Uploaded " + Request.Files.Count + " files");
}