使用mvc3中的plupload将图像显示在同一视图上,并将图像上传到数据库

时间:2013-09-12 05:37:46

标签: c# jquery asp.net-mvc-3

i want to display images as they are uploaded using plupload , images are getting stored in database but i want them to show on screen as they are saved to database and when images are saved it is not submiting using form as below validation is never checked for more than 8files .i have no idea how to go about it.

我只是希望图像在uploadimages div中显示,因为它们将保存在db。

below is my view :
<link href="@Url.Content("~/Scripts/plupload/js/jquery.plupload.queue/css/jquery.plupload.queue.css")"
    rel="stylesheet" type="text/css" />
<link href="@Url.Content("~/Scripts/plupload/js/jquery.ui.plupload/css/jquery.ui.plupload.css")"
    rel="stylesheet" type="text/css" />
<script src="@Url.Content("~/Scripts/plupload/js/plupload.full.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/plupload/js/jquery.ui.plupload.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/plupload/js/jquery.plupload.queue/jquery.plupload.queue.js")" type="text/javascript"></script>
<script type="text/javascript">


    $(document).ready(function () {

        $("#uploader").pluploadQueue({
            // General settings
            runtimes: 'html5,html4,gears,flash,silverlight',
            url: '@Url.Action("ImageUpload")',
            max_file_size: '10mb',
            chunk_size: '1mb',
            unique_names: true,
            button_browse_hover: true,
            multiple_queues: true,
            dragdrop: false,

            // Resize images on clientside if we can
            resize: { width: 320, height: 340, quality: 90 },

            // Specify what files to browse for
            filters: [
                { title: "Image files", extensions: "jpg,gif,png,jpeg,bmp" },
                { title: "Zip files", extensions: "zip" },
                { title: 'PDF files', extensions: 'pdf' },
                { title: "Excel Files", extensions: "xls,xslx,csv" },

            ],



            // Silverlight settings
            silverlight_xap_url: '@Url.Content("~/Scripts/plupload/plupload.silverlight.xap")'
        });

        // Client side form validation
        $('form').submit(function (e) {

            var uploader = $('#uploader').pluploadQueue();
            // Files in queue upload them first
            if (uploader.files.length > 0) {

                if (uploader.files.length < 9) {
                    // When all files are uploaded submit form
                    uploader.bind('StateChanged', function () {
                        if (uploader.files.length === (uploader.total.uploaded + uploader.total.failed)) {

                            $('form')[0].submit();

                        }
                    });
                    uploader.bind('FileUploaded', function (data) {

                        $('#uploadedImages').prepend('<img id="theImg" src="' + data + '" />');

                    });
                    uploader.start();
                } else {
                    alert('Number of files more than 8.');
                }
                return false;
            }
            else {
                alert('You must queue at least one file.');
            }
            return false;
        });



    });


</script>
@using (Html.BeginForm("ImageUpload", "Image", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div id="uploader">
        <p>
            You browser doesn't have Flash, Silverlight, Gears, BrowserPlus or HTML5 support.</p>
    </div>



}
<div id="uploadedImages">
</div>

以下是控制器:

在此我保存了数据库并返回UploadedImage以显示在同一视图上。

 [HttpPost]
        public string ImageUpload(HttpPostedFileBase uploadFile)
        {
            var bytes = new byte[0];
            int patientId = (int)TempData["PatientId"];
            TempData.Keep();
            string UploadedImage = string.Empty;
            PatientChartImage oPatientChartImage = new PatientChartImage();

            uploadFile = Request.Files[0];

            if (uploadFile.ContentLength > 0)
            {
                bytes = new byte[uploadFile.ContentLength];
                var fileName = Path.GetFileName(uploadFile.FileName);
                var path = Path.Combine(Server.MapPath("~/TempFolder"), fileName);
                oPatientChartImage.PatientId = patientId;
                oPatientChartImage.PracticeId = (User as CustomPrincipal).CustomIdentity.PracticeId;
                oPatientChartImage.Title = fileName;
                oPatientChartImage.UserId = (User as CustomPrincipal).CustomIdentity.UserId;
                oPatientChartImage.SerialNumber = 2;

                Bitmap original = Bitmap.FromStream(uploadFile.InputStream) as Bitmap;

                using (System.IO.MemoryStream stream = new System.IO.MemoryStream())
                {
                    original.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
                    oPatientChartImage.Image= stream.ToArray();
                    UploadedImage = ViewBag.ImageData = "data:image/png;base64," + Convert.ToBase64String(stream.ToArray());

                }

                db.PatientChartImages.Add(oPatientChartImage);
                db.SaveChanges();

            }
            //return Json(new { ImageData = UploadedImage },JsonRequestBehavior.AllowGet);
            return UploadedImage;
        }

1 个答案:

答案 0 :(得分:0)

我觉得使用Ajax上传比使用任何其他插件更好..

你的HomeController是这样的,

public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public WrappedJsonResult UploadImage(HttpPostedFileWrapper imageFile)
        {
            if (imageFile == null || imageFile.ContentLength == 0)
            {
                return new WrappedJsonResult
                {
                    Data = new
                    {
                        IsValid = false,
                        Message = "No file was uploaded.",
                        ImagePath = string.Empty
                    }
                };
            }

            var fileName = String.Format("{0}.jpg", Guid.NewGuid().ToString());
            var imagePath = Path.Combine(Server.MapPath(Url.Content("~/Uploads")), fileName);

            imageFile.SaveAs(imagePath);

            return new WrappedJsonResult
            {
                Data = new
                {
                    IsValid = true,
                    Message = string.Empty,
                    ImagePath = Url.Content(String.Format("~/Uploads/{0}", fileName))
                }
            };
        }
    }

为JsonResult添加一个单独的类

public class WrappedJsonResult : JsonResult
    {
        public override void ExecuteResult(ControllerContext context)
        {
            context.HttpContext.Response.Write("<html><body><textarea id=\"jsonResult\" name=\"jsonResult\">");
            base.ExecuteResult(context);
            context.HttpContext.Response.Write("</textarea></body></html>");
            context.HttpContext.Response.ContentType = "text/html";
        }
    }

您的观点就像是,

@using (Html.BeginForm("UploadImage", "Home", FormMethod.Post, 
    new { enctype = "multipart/form-data", id="ImgForm", 
        name="ImgForm", target="UploadTarget" }))
{
    <h3>Upload Image</h3>
    <input type="file" name="imageFile" />

    <input type="button" value="Save Image" onclick="UploadImage()" />
}
<iframe id="UploadTarget" name="UploadTarget" onload="UploadImage_Complete();" style="position: absolute; left: -999em; top: -999em;"></iframe>
<div id="Images"></div>

<script type="text/javascript">
    var isFirstLoad = true;

    function UploadImage() {
        $("#ImgForm").submit();
    }

    function UploadImage_Complete() {
        //Check to see if this is the first load of the iFrame
        if (isFirstLoad == true) {
            isFirstLoad = false;
            return;
        }

        //Reset the image form so the file won't get uploaded again
        document.getElementById("ImgForm").reset();

        //Grab the content of the textarea we named jsonResult .  This shold be loaded into 
        //the hidden iFrame.
        var newImg = $.parseJSON($("#UploadTarget").contents().find("#jsonResult")[0].innerHTML);

        //If there was an error, display it to the user
        if (newImg.IsValid == false) {
            alert(newImg.Message);
            return;
        }

        //Create a new image and insert it into the Images div.  Just to be fancy, 
        //we're going to use a "FadeIn" effect from jQuery
        var imgDiv = document.getElementById("Images");
        var img = new Image();
        img.src = newImg.ImagePath;

        //Hide the image before adding to the DOM
        $(img).hide();
        imgDiv.appendChild(img);
        //Now fade the image in
        $(img).fadeIn(500, null);
    }

</script>

编写用于将图片插入数据库的代码。希望它可以帮助某人! :)