Chọn hình từ PC và hiển thị lên browser với Asp.Net MVC


12/03/2020- duocnt    4960 Views    

Ứng dụng hoàn thành sẽ như sau:

pickup image 1


Các bước thực hiện:

  1. Tạo database và table.
  2. Tạo project và generate entity từ database.
  3. Viết các phương thức thao tác dữ liệu (DAO).
  4. Tạo controller "Post" và viết các ActionResult, JsonResult.
  5. Tạo folder "uploadedImagestrong project.
  6. Tạo View từ ActionResult.
  7. Viết các phương thức jQuery để upload file hình khi được chọn. Xử lý sự kiện Change của input file. View hình lên webpage sau khi hình được upload.
  8. Video clip chi tiết.
  9. Source code github.




Thực hiện:

1 - Tạo Database và table trong SQL Server.

2 - Tạo project Asp.Net MVC và generate entity từ database.












3 - Viết các phương thức tao tác với dữ liệu (DAO).
 - Tạo folder DAO trong project

 - Tạo class PostDAO trong folder DAO.

 - Source code của class PostDAO.cs.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using PickupImage.Models;
namespace PickupImage.DAO
{
    public class PostDAO
    {
        pickupimageDb db;
 
        public PostDAO()
        {
            db = new pickupimageDb();
        }
 
 
        /// <summary>
        /// Create new Post
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool create(Post entity)
        {
            try
            {
                db.Posts.Add(entity);
                db.SaveChanges();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }
 
 
        /// <summary>
        /// For edit existing Post
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public bool edit(Post entity)
        {
            try
            {
                var model = db.Posts.Find(entity.id);
                model.title = entity.title;
                model.Content = entity.Content;
                model.ImagePath = entity.ImagePath;
                db.SaveChanges();
                return true;
            }
           catch (Exception ex)
            {
                return false;
            }
        }
        /// <summary>
        /// Find Post object by id
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public PostfindById(int id)
        {
            Post model = db.Posts.Find(id);
            return model;
        }
    }
}

4 - Tạo controller Post, viết các ActionResult và JsonResult.

 - Source code của PostController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using PickupImage.DAO;
using PickupImage.Models;
namespace PickupImage.Controllers
{
    public class PostController : Controller
    {
        PostDAO dao;
        // GET: Post
        public ActionResult Index()
        {
            return View();
        }
        [HttpGet]
        public ActionResult create()
        {
            return View();
        }
        [HttpPost]
        public ActionResult create(Post entity)
        {
            dao = new PostDAO();
            bool result = dao.create(entity);
            return View(entity);
        }
        [HttpGet]
        public ActionResult edit(int id)
        {
            dao = new PostDAO();
            var model = dao.findById(id);
            return View(model);
        }
        [HttpPost]
        public ActionResult edit(Post entity)
        {
            dao = new PostDAO();
            if (ModelState.IsValid)
            {
                bool result = dao.edit(entity);            
            }
            return View(entity);
        }
        [HttpPost]
        /// <summary>
        /// This method wil be call from client via Ajax jQuery.
        /// </summary>
        /// <param name="file"></param>
        /// <returns></returns>
        public JsonResult SaveFile(HttpPostedFileBase file)
        {
            string returnImagePath = string.Empty;
            if (file.ContentLength > 0)
            {
                string fileName, fileExtension, imaageSavePath;
                fileName = Path.GetFileNameWithoutExtension(file.FileName);
                fileExtension = Path.GetExtension(file.FileName);
                imaageSavePath = Server.MapPath("/uploadedImages/") + fileName + fileExtension;
                //Save file
                file.SaveAs(imaageSavePath);
                //Path to return
       returnImagePath = "/uploadedImages/" + fileName + fileExtension;
            }
            return Json(returnImagePath, JsonRequestBehavior.AllowGet);
        }
    }
}

 5 - Tạo folder "uploadedImagestrong project.
 - Folder này dùng để lưu hình khi được chọn từ client.

6 - Tạo View từ ActionResult create().
 - Sau khi tạo View (create.cshtml), chỉnh sửa lại nhóm model.ImagePath.





7 - Viết các phương thức jQuery để upload file hình khi được chọn.Xử lý sự kiện Change của input type file.
 - Phương thức uploadImage(): Phương thức này dùng để upload file hình sau khi được chọn bằng cách gọi tới JsonResult SaveFile() thuộc PostController.

        //First, create a method to upload image to server after picked from PC
        function uploadImage(file) {
            var formData = new FormData();
            formData.append("file", file);
            $.ajax({
                data: formData,
                type: "POST",
                url: '/Post/SaveFile',
                cache: false,
                contentType: false,
                processData:false,
                success: function (returnImageURL) {
                    //Asign return Image URL to HTML.Hiddenfor
                    $('#ImagePath').val(returnImageURL);
                    //Call this method to view Image
                    ViewImage(returnImageURL);
                }              
            });
        }

 - Phương thức ViewImage(url): phương thức này sẽ dùng để hiển thị image lên webpage sau khi hình được upload lên server. 

        //View Image
        function ViewImage(url) {
            if (url) {
                $('#ImageViewing').attr('src', url);
            }
        }

  - Sự kiện change() của input type=file.

        //Now handle change Event of Input type file
        $('#pickupImage').change(function () {
            //call upload method
            uploadImage(this.files[0]);
        });

 - Source code jQuery đầy đủ, viết trong @section Scripts{}

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
    <script type="text/javascript">
        //View Image when webpage is loaded
        var url = $('.ImagePath').val();
        ViewImage(url);
        //Now handle change Event of Input type file
        $('#pickupImage').change(function () {
            //call upload method
            uploadImage(this.files[0]);
        });
        //First, create a method to upload image to server after picked from PC
        function uploadImage(file) {
            var formData = new FormData();
            formData.append("file", file);
            $.ajax({
                data: formData,
                type: "POST",
                url: '/Post/SaveFile',
                cache: false,
                contentType: false,
                processData:false,
                success: function (returnImageURL) {
                    //Asign return Image URL to HTML.Hiddenfor
                    $('#ImagePath').val(returnImageURL);
                    //Call this method to view Image
                    ViewImage(returnImageURL);
                }              
            });
        }
        //View Image
        function ViewImage(url) {
            if (url) {
                $('#ImageViewing').attr('src', url);
            }
        }
    </script>
}

8 - Video clip chi tiết.

9 - Source code
- Download source code: PickupImageInMVC


Góp ý kiến

;
;