9

我正在 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");
                    }
            });

但是现在我还需要上传他的图片,但是我找不到任何可以使用这种方法的方法,或者没有任何没有回发的方法。

我知道将 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);
        }

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

请帮忙

谢谢。

4

7 回答 7

44

HTML 代码

<input type="file"  id="uploadEditorImage"  />

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);
        }

    });
});

MVC 控制器中的代码

if (System.Web.HttpContext.Current.Request.Files.AllKeys.Any())
        {
            var pic = System.Web.HttpContext.Current.Request.Files["HelpSectionImages"];
        }
于 2014-09-10T14:35:20.387 回答
10

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

<input type="file" name="etlfileToUpload" id="etlfileToUpload"  />

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.");
}

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

于 2013-01-29T04:54:22.933 回答
1

试试这个它对我有用

   <input type="file" name="Upload" id="Upload" />

$('#Upload').change(function () {
    debugger;
    var file = document.getElementById('Upload').files[0];
    var fileName = file.name;
    var fd = new FormData();
    fd.append("fileData", file);
    fd.append("key", '@Model.Id');

    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", "/ImageHandler.ashx", 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.");
}

处理程序:

public class ImageHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        //context.Response.ContentType = "text/plain";
        //context.Response.Write("Hello World");]



        string filePath = Constants.ImageFolderPath;

        //write your handler implementation here.
        if (context.Request.Files.Count <= 0)
        {
            context.Response.Write("No file uploaded");
        }
        else
        {
            for (int i = 0; i < context.Request.Files.Count; ++i)
            {
                HttpPostedFile file = context.Request.Files[i];
                if (context.Request.Form != null)
                {
                    string imageid = context.Request.Form.ToString();
                    imageid = imageid.Substring(imageid.IndexOf('=') + 1);

                    if (file != null)
                    {
                        string ext = file.FileName.Substring(file.FileName.IndexOf('.'));
                        if (ext.ToLower().Contains("gif") || ext.ToLower().Contains("jpg") || ext.ToLower().Contains("jpeg") || ext.ToLower().Contains("png"))
                        {

                            byte[] data;
                            using (Stream inputStream = file.InputStream)
                            {
                                MemoryStream memoryStream = inputStream as MemoryStream;
                                if (memoryStream == null)
                                {
                                    memoryStream = new MemoryStream();
                                    inputStream.CopyTo(memoryStream);
                                }
                                data = memoryStream.ToArray();
                                File.WriteAllBytes(Constants.ImageFolderPath + imageid + ".jpg", (byte[])data);
                                //club.club_image = Convert.ToBase64String(data);
                            }
                        }
                    }
                }
                else
                {

                }

                //file.SaveAs(context.Server.MapPath(filePath + file.FileName));
                context.Response.Write("File uploaded");
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
于 2013-12-03T12:53:32.617 回答
1

我个人不喜欢使用除 java script、css 或 html 之外的任何第三方工具。我将采用 UmairP 展示的第一种方法。但是,如果您想节省自己编写大量代码的时间。这是一个不错的jquery插件

还有一个带有这个插件的 asp.net mvc演示

请看一看。让我知道是否需要任何进一步的信息。

于 2013-01-29T05:36:36.153 回答
1
$(document).ready(function(){
   var status = $('#status');

        $('#frmUpload').ajaxForm({
            beforeSend: function () {
                if ($("#file").val() != "") {                   
                    $("#progressDiv").show();                    
                }
                status.empty();
            },
            success: function () {
                showTemplateManager();
            },
            complete: function (xhr) {
                if ($("#file").val() != "") {
                    var millisecondsToWait = 500;
                    setTimeout(function () {                       
                     $("#progressDiv").hide();
                    }, millisecondsToWait);
                }
                status.html(xhr.responseText);
            }
        });
});
于 2015-07-24T15:42:10.517 回答
0

我也遇到了类似的问题,在坚持了很多天之后,这个链接终于帮助了我

带有进度条的 Jquery Uploadiy 与 MVC 一起使用

这就是我管理它的方式

public JsonResult Upload(HttpPostedFileBase file)
{
    if (Session["myAL"] == null)
    {
        al = new ArrayList();
    }
    else
        al = (ArrayList)Session["myAL"];

    var uploadFile = file;

        if (uploadFile != null && uploadFile.ContentLength > 0)
        {
            string filePath = Path.Combine(HttpContext.Server.MapPath("~/Content/Uploads"),
                                               Path.GetFileName(uploadFile.FileName));                    
            al.Add(filePath);
            Session["myAL"] = al;
            uploadFile.SaveAs(filePath);
        }

    var percentage = default(float);

    if (_totalCount > 0)
    {
        _uploadCount += 1;
        percentage = (_uploadCount / _totalCount) * 100;
    }

    return Json(new
    {
        Percentage = percentage
    });
}

如何在 MVC 和 jquery 中为 FileUploading 实现附加更多文件

于 2013-06-25T12:22:45.860 回答
0
<input type="file" name="file" id="file" style="width: 100%;"onchange="readURL(this);" />

 if (file != null && file.ContentLength > 0)
                {
                    string filename = Path.GetFileName(file.FileName);
                    string imgpath = Path.Combine(Server.MapPath("~/Img/"), filename);
                    file.SaveAs(imgpath);
                    student.photo = imgpath;
                }

function readURL(input)
    {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#imgUser')
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }
于 2018-08-24T19:06:33.350 回答