如何实现在MVC和jquery中附加更多文件以进行文件上载

时间:2013-01-28 13:25:35

标签: javascript jquery asp.net-mvc-3 asp.net-mvc-4

在雅虎的帖子中,当附加文件时,按下它时会出现一个“附加更多文件”按钮,它将成为插入文件的一个字段。 这是代码:

<a href = "javascript: addUploadFields ();" id = "attach_more"> Attach more files </ a>

我如何实现MVC?

5 个答案:

答案 0 :(得分:0)

使用文件上传控件上传多个文件时,我使用简单易用的JQuery Multifile插件。请参阅此链接JQuery Multiple File Upload

只是包含了这个库和JQuery,它的语法就像

<input type="file" class="multi"/>

答案 1 :(得分:0)

  1. 创建一个允许您上传文件的控制器和操作

  2. 找到一个实现上传多个文件的客户端插件。我发现工作得很好的是Kendo UI

  3. 上传插件

    如果您使用Kendo UI,这应该可以帮助您入门:

    控制器:

       [HttpPost]
        public ActionResult Save(HttpPostedFileBase[] files) {
            // The Name of the Upload component is "attachments"
            foreach (var file in files) {
                //Do Something
            }
            // Return an empty string to signify success
            return Content("");
        }
    

    查看

    <form action="/Controller/Action" method="post" enctype="multipart/form-data">
     <input type="file" name="files[]" id="file" />
    ...
    </form>
    

答案 2 :(得分:0)

这与https://stackoverflow.com/questions/14575787/几乎相同。插件支持多文件上传。如果需要更多细节,请告诉我。

答案 3 :(得分:0)

您可以使用许多文件上传器,例如

this

您可以使用此代码进行上传 这段代码是客户端:

<form enctype="multipart/form-data">
<input name="file" type="file" />
<input type="button" value="Upload" />
</form>
<progress></progress>

首先,如果需要,您可以进行一些验证。例如,在文件的onChange事件中。

    $(':file').change(function(){
        var file = this.files[0];
        name = file.name;
        size = file.size;
        type = file.type;
        //your validation
    });

$(':button').click(function(){
    var formData = new FormData($('form')[0]);
    $.ajax({
        url: 'url',  //server script to process data
        type: 'POST',
        xhr: function() {  // custom xhr
            myXhr = $.ajaxSettings.xhr();
            if(myXhr.upload){ // check if upload property exists
                myXhr.upload.addEventListener('progress',progressHandlingFunction, false); // for handling the progress of the upload
            }
            return myXhr;
        },
        //Ajax events
        beforeSend: beforeSendHandler,
        success: completeHandler,
        error: errorHandler,
        // Form data
        data: formData,
        //Options to tell JQuery not to process data or worry about content-type
        cache: false,
        contentType: false,
        processData: false
    });
});

function progressHandlingFunction(e){
    if(e.lengthComputable){
        $('progress').attr({value:e.loaded,max:e.total});
    }
}

这是你的控制器

 [HttpPost]
    public ActionResult Save(HttpPostedFileBase[] files) {
        // The Name of the Upload component is "attachments"
        foreach (var file in files) {
            //Do Something
        }
        // Return an empty string to signify success
        return Content("");
    }

所以如果你不想使用ajax使用这个

@{
    ViewBag.Title = "Upload";
}
<h2>
    Upload</h2>

@using (Html.BeginForm(actionName: "Upload", controllerName: "User", 
                       method: FormMethod.Post,
                       htmlAttributes: new { enctype = "multipart/form-data" }))
{
    <text>Upload a photo:</text> <input type="file" name="files"  multiple />
    <input type="submit" value="Upload" />
}

答案 4 :(得分:0)

经过许多不成功的解决方案,我从

获得了它
http://lbrtdotnet.wordpress.com/2011/09/02/asp-net-mvc-multiple-file-uploads-using-uploadify-and-jqueryui-progressbar/

click this useful link

 I kept the Url Values in a session



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

然后在我的帖子创建操作中检索它们

public ActionResult MultimediaCreate(MultimediaModel newMultimedia)
    {            
        if (ModelState.IsValid)
        {
            db.submitMultimedia(newMultimedia);
            al = (ArrayList)Session["myAL"];
            foreach(string am in al)
            {
                MarjaaEntities me = new MarjaaEntities();
                MultimediaFile file = new MultimediaFile();
                file.MultmediaId = newMultimedia.id;
                file.MultimediaFileUrl = am;
                me.MultimediaFiles.AddObject(file);
                me.SaveChanges();
                Session.Remove("myAL");
            }
            return RedirectToAction("MultimediaIndex");
        }
        return View();
    }