- [DEVEXPRESS] Hỗ trợ tìm kiếm highlight không dấu và không khoảng cách trên Gridview Filter
- [C#] Chia sẻ source code phần mềm Image Downloader tải hàng loạt hình ảnh từ danh sách link url
- [C#] Chụp hình và quay video từ camera trên winform
- [C#] Chia sẽ full source code tách file Pdf thành nhiều file với các tùy chọn
- Giới thiệu về Stock Tracker Widget - Công cụ theo dõi cổ phiếu và cảnh báo giá tăng giảm bằng C# và WPF
- [VB.NET] Chia sẻ công cụ nhập số tiền tự động định dạng tiền tệ Việt Nam
- [VB.NET] Hướng dẫn fill dữ liệu từ winform vào Microsoft word
- [VB.NET] Hướng dẫn chọn nhiều dòng trên Datagridview
- Hướng Dẫn Đăng Nhập Nhiều Tài Khoản Zalo Trên Máy Tính Cực Kỳ Đơn Giản
- [C#] Chia sẻ source code phần mềm đếm số trang tập tin file PDF
- [C#] Cách Sử Dụng DeviceId trong C# Để Tạo Khóa Cho Ứng Dụng
- [SQLSERVER] Loại bỏ Restricted User trên database MSSQL
- [C#] Hướng dẫn tạo mã QRcode Style trên winform
- [C#] Hướng dẫn sử dụng temp mail service api trên winform
- [C#] Hướng dẫn tạo mã thanh toán VietQR Pay không sử dụng API trên winform
- [C#] Hướng Dẫn Tạo Windows Service Đơn Giản Bằng Topshelf
- [C#] Chia sẻ source code đọc dữ liệu từ Google Sheet trên winform
- [C#] Chia sẻ source code tạo mã QR MOMO đa năng Winform
- [C#] Chia sẻ source code phần mềm lên lịch tự động chạy ứng dụng Scheduler Task Winform
- [C#] Hướng dẫn download file từ Minio Server Winform
[C#] Hướng dẫn upload file, hình ảnh từ Winform lên server API ASP.NET Core
Xin chào các bạn, bài viết hôm nay mình sẻ tiếp tục hướng dẫn các bạn cách viết một API upload file hình ảnh sử dụng ASP.NET Core, và sử dụng Winform để chọn file upload lên Server.
[C#] Build API server upload file, image ASP.NET core
Bước 1: Tạo một solution để build API upload file
Để API Upload này chúng ta sẽ kiểm tra 2 loại sau:
- Chỉ cho phép upload những loại file do chúng ta chỉ định: jpg, png, gif,...
- Giới hạn dung lượng file upload (Ví dụ: Limit upload image >2 MB)
Và dĩ nhiên các bạn có thể bỏ qua 2 lựa chọn trên để cho phép upload tùy ý.
kết quả khi thực hiện API, thành công hay thất bại vào key status trên json trả về, chi tiết các bạn tham khảo các hình ảnh bên dưới.
Giao diện Test upload file qua API sử dụng Winform:

Full Code HomeController.cs (upload API):
[HttpPost]
public async Task<IActionResult> UploadFileAsync(List<IFormFile> file)
{
    const bool AllowLimitSize = true;
    const bool AllowLimitFileType = true;
    var limitFileSize = 2097152; // allow upload file less 2MB = 2097152
    var listFileError = new List<FileUploadInfo>();
    var responseData = new ResponseData();
    string result = "";
    if(file.Count <= 0)
    {
        responseData.status = "ERROR";
        responseData.message = $"Please, select file to upload.";                
        result = JsonConvert.SerializeObject(responseData);
        return Ok(result);
    }
    var listFileTypeAllow = "jpg|png|gif|xls|xlsx";   
   
    if (listFileError.Count > 0)
    {
        responseData.status = "ERROR";
        responseData.data = JsonConvert.SerializeObject(listFileError);
        responseData.message = $"File type upload only Allow Type: ({listFileTypeAllow}) {responseData.data}";
        result = JsonConvert.SerializeObject(responseData);
        return Ok(result);
    }
    // check list file less limit size
    if (AllowLimitSize)
    {
        foreach (var formFile in file)
        {
            if (formFile.Length > limitFileSize)
            {
                listFileError.Add(new FileUploadInfo()
                {
                    filename = formFile.FileName,
                    filesize = formFile.Length
                });
            }
        }
    }
   
    var listLinkUploaded = new List<string>();
    if (listFileError.Count > 0)
    {
        responseData.status = "ERROR";
        responseData.data = JsonConvert.SerializeObject(listFileError);
        responseData.message = $"File upload must less 2MB ({ responseData.data})";
        result = JsonConvert.SerializeObject(responseData);
        return Ok(result);
    }
   
    foreach (var formFile in file)
    {
        if (formFile.Length > 0)
        {
            var templateUrl = formFile.FileName;
            string filePath = Path.Combine($"{_webHost.WebRootPath}/uploads/", templateUrl);
            string fileName = Path.GetFileName(filePath);
            using (var stream = System.IO.File.Create(filePath))
            {
                await formFile.CopyToAsync(stream);
            }
            listLinkUploaded.Add($"{baseUrl}/uploads/{formFile.FileName}");
        }
    }
    responseData.status = "SUCCESS";
    responseData.data = JsonConvert.SerializeObject(listLinkUploaded);
    responseData.message = $"uploaded {file.Count} files successful.";
    result = JsonConvert.SerializeObject(responseData);
    return Ok(result);
}Kết quả khi chạy API thuộc những loại file type không cho phép upload sẽ trả về json như hình dưới:

Kết quả API trả về nếu dung lượng file upload quá cho phép:

Và hình ảnh cuối cùng nếu chúng ta upload file thành công => trả về list đường dẫn tập tin

Source code Test upload File trên Winform sử dụng Webclient Upload File Async:
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TestUpload
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void btn_upload_Click(object sender, EventArgs e)
        {
            var API_UPLOAD = "http://localhost:45320/api/Home/UploadFile";
            using(var dlg = new OpenFileDialog())
            {
                dlg.Multiselect = true;
                if(dlg.ShowDialog() == DialogResult.OK)
                {
                    foreach (var filename in dlg.FileNames)
                    {
                        var client = new WebClient();
                        client.Headers.Add("Content-Type", "binary/octet-stream");                        
                        client.UploadFileAsync(new Uri(API_UPLOAD), filename);                      
                        client.UploadFileCompleted += Client_UploadFileCompleted;
                        client.UploadProgressChanged += Client_UploadProgressChanged;
                    }
                    
                }
            }
        }
        private void Client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e)
        {
            progressBar1.BeginInvoke(new Action(() => {
                var percent = e.BytesSent * 100 / e.TotalBytesToSend;              
                Console.WriteLine(percent + "");
                    progressBar1.Value = (int)percent;
                    label1.Text = percent.ToString() + "%";
                
                    
            }));
        }
        private void Client_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e)
        {
            var data = Encoding.UTF8.GetString(e.Result);
            var responseData = JsonConvert.DeserializeObject<ResponseData>(data);
            if (responseData.status == "SUCCESS")
            {
                var link = JsonConvert.DeserializeObject<List<string>>( responseData.data);
                pictureBox1.LoadAsync(link.FirstOrDefault());
            }
            else
            {
                MessageBox.Show(responseData.message);
            }
            
        }
        public class ResponseData
        {
            public string status { get; set; }
            public string message { get; set; }
            public string data { get; set; }
        }
    }
}
Thanks for watching!

![[C#] Hướng dẫn upload file, hình ảnh từ Winform lên server API ASP.NET Core](https://laptrinhvb.net/uploads/users/9a8cb514e4428e85fb4ca07588e9103f.png)

![[C#] Hướng dẫn gom như thư viện dll vào một thư mục đặc biệt tách rời file chạy exe winform](https://laptrinhvb.net/uploads/source/csharp/gom_dll_thumb.png)
![[C#] Chia sẻ source code phần mềm Image Downloader tải hàng loạt hình ảnh từ danh sách link url](https://laptrinhvb.net/uploads/source/new_image_baiviet/tool_image_downloader.png)
![[C#] Tạo hiệu ứng Window Matrix Effect](https://laptrinhvb.net/uploads/source/vbnet/window_matrix_effect.png)
![[C#] Giới thiệu và hướng dẫn sử dụng Parallel trong lập trình .NET](https://laptrinhvb.net/uploads/source/image_baiviet/5990336db101f6d4f4fe555a8702d5a5.png)
![[C#] Hướng dẫn Flip Image Winform](https://laptrinhvb.net/uploads/source/csharp/flip_Image_csharp.gif)
![[C#] Dependency Injection in Winform](https://laptrinhvb.net/uploads/source/new_image_baiviet/dependency_csharp_winform.png)

![[C#] Thiết kế ứng dụng Single Instance và đưa ứng dụng lên trước nếu kiểm tra ứng dụng đang chạy](https://laptrinhvb.net/uploads/source/new_image_baiviet/single_intance_thumb.png)
![[C#] Hướng dẫn chia sẽ share thư mục folder trong winform](https://laptrinhvb.net/uploads/source/csharp/share_folder_csharp_thumb.jpg)
![[C#] Hướng dẫn viết app Auto Typer từ clipboard](https://laptrinhvb.net/uploads/source/new_image_baiviet/auto_typing_csharp.png)
![[C#] Chia sẽ class BackGroundOverlay Show Modal cho Winform](https://laptrinhvb.net/uploads/source/csharp/modal_overlay.png)
![[C#] Hướng dẫn sử dụng thư viện FluentValidation để kiểm tra Form nhập liệu winform](https://laptrinhvb.net/uploads/source/csharp/fluent_validate_csharp.png)
![[C#] Hướng dẫn thiết kế Label Vertical Align Text trong Winform](https://laptrinhvb.net/uploads/source/csharp/vertical_align_text_thumb.png)
![[C#] Hướng dẫn gộp tất cả các file thư viện dll và file chạy exe thành một file exe duy nhất sử dụng Microsoft ILMerge](https://laptrinhvb.net/uploads/source/csharp/ilmerge.png)
![[C#] Hướng dẫn tạo Windows Services đơn giản Winform](https://laptrinhvb.net/uploads/source/vbnet/windows_services_thumb.jpg)
![[C#] Thêm ứng dụng vào Taskbar sử dụng SharpShell DeskBand](https://laptrinhvb.net/uploads/source/vbnet/net_monitor_deskband_csharp.gif)
![[C#] Hướng dẫn download tất cả image trên website về ổ đĩa local](https://laptrinhvb.net/uploads/source/image_baiviet/00e89e167e1a60e86fe636d9a81f803a.png)
![[C#] Hướng dẫn thêm, lưu, xóa, sửa, tìm kiếm trên SQLSERVER CE (SQL COMPACT)](https://laptrinhvb.net/uploads/source/image_baiviet/9695e729194410d52eb4a1e8234e9e0c.jpg)
![[C#] Kiểm tra đường dẫn website có tồn tại hay không?](https://laptrinhvb.net/uploads/source/csharp/check_url_exists_thumb.jpg)
![[C#] Mã hóa văn bản text sử dụng thuật toán AES Winform](https://laptrinhvb.net/uploads/source/csharp/aes_csharp_thumb.png)
![[C#] Hướng dẫn viết ứng dụng check live SSH Server](https://laptrinhvb.net/uploads/source/image_baiviet/6bc4d5b0ca4995dfce771849892f925e.jpg)
![[C#] Sử dụng DotNetBrowser nhân Chromium giải pháp thay thế WebBrowser trên Winform](https://laptrinhvb.net/uploads/source/vbnet/dot_net_browser_thumb.jpg)
![[C#] Hướng dẫn sử dụng Tab Order thiết lập Tab Index cho từng control](https://laptrinhvb.net/uploads/source/csharp/tab_order_csharp.png)
![[C#] Hướng dẫn sử dụng Transaction sql trong lập trình csharp](https://laptrinhvb.net/uploads/source/csharp/transaction_csharp_thumb.jpg)
![[C#] Hướng dẫn  Sử dụng IL Disassembler (ildasm.exe) và IL Assembler (ilasm.exe) để chỉnh sửa mã nguồn](https://laptrinhvb.net/uploads/source/image_baiviet/0c229a6edeb81108fd9b7d100f929778.png)
