如何在没有回发的情况下使用ajax或任何其他技术在ASP.NET MVC 4中上传图像?

use*_*290 9 file-upload c#-4.0 asp.net-mvc-4

我正在开发一个MVC 4的网站,用户填写一些信息并保存到上传.除了图像之外的所有信息都使用Javascript,Json和Ajax保存在服务器上,如下所示:

$.ajax({
                    url: action,
                    type: "POST",
                    data: JSON.stringify(PostViewModel),
                    dataType: "json",
                    contentType: "application/json; charset=utf-8",
                    beforeSend: function () {            
                    },
                    success: function (data) {
                    try{
                        alert('success');
                    }catch(err){alert(' Error: '+err);}

                    },
                    complete: function () {
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        alert("Error occured");
                    }
            });
Run Code Online (Sandbox Code Playgroud)

但是现在我也需要上传他的图像​​,但我找不到任何可以使用这种方法的方法或任何没有回发的方法.

我知道将FileUpload Control放在Form标签中并按下提交按钮我可以获得如下所示的图像文件:

 HttpPostedFileBase photo = Request.Files["photo"];
        if (photo != null)
        {
            Session["ImgPath"] = "~/Content/PostImages/" + photo.FileName;
            string path = Server.MapPath("~/Content/PostImages/");
            photo.SaveAs(path + photo.FileName);
        }
Run Code Online (Sandbox Code Playgroud)

但对于这种方法,我将不得不改变我保存内容的方法(使用Javascript,Json和Ajax),我不能.

请帮忙

谢谢.

She*_*R A 40

HTML代码

<input type="file"  id="uploadEditorImage"  />
Run Code Online (Sandbox Code Playgroud)

Javascript代码

$("#uploadEditorImage").change(function () {
    var data = new FormData();
    var files = $("#uploadEditorImage").get(0).files;
    if (files.length > 0) {
        data.append("HelpSectionImages", files[0]);
    }
    $.ajax({
        url: resolveUrl("~/Admin/HelpSection/AddTextEditorImage/"),
        type:"POST",
        processData: false,
        contentType: false,
        data: data,
        success: function (response) {
           //code after success

        },
        error: function (er) {
            alert(er);
        }

    });
});
Run Code Online (Sandbox Code Playgroud)

MVC控制器中的代码

if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
        {
            var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
        }
Run Code Online (Sandbox Code Playgroud)

  • 很好,很整洁的答案. (2认同)

U.P*_*U.P 9

有两种异步发布文件(图像)的方法如果目标浏览器支持文件api,则可以使用以下内容:HTML:

<input type="file" name="etlfileToUpload" id="etlfileToUpload"  />
Run Code Online (Sandbox Code Playgroud)

JavaScript的

// Call this function on upload button click after user has selected the file 
function UploadFile() {
    var file = document.getElementById('etlfileToUpload').files[0];
    var fileName = file.name;    
    var fd = new FormData();    
    fd.append("fileData", file);    
    var xhr = new XMLHttpRequest();
    xhr.upload.addEventListener("progress", function (evt) { UploadProgress(evt); }, false);
    xhr.addEventListener("load", function (evt) { UploadComplete(evt); }, false);
    xhr.addEventListener("error", function (evt) { UploadFailed(evt); }, false);
    xhr.addEventListener("abort", function (evt) { UploadCanceled(evt); }, false);
    xhr.open("POST", "{URL}", true); 
    xhr.send(fd);
}


function UploadProgress(evt) {
    if (evt.lengthComputable) {
        var percentComplete = Math.round(evt.loaded * 100 / evt.total);
        $("#uploading").text(percentComplete + "% ");        
    }
}

function UploadComplete(evt) {
    if (evt.target.status == 200)
        alert(evt.target.responseText);
    else {
        alert("Error Uploading File");
    }
}

function UploadFailed(evt) {    
    alert("There was an error attempting to upload the file.");
}

function UploadCanceled(evt) {    
    alert("The upload has been canceled by the user or the browser dropped the connection.");
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用像uploadify这样的swf工具