'dotnet core'에 해당되는 글 1건

webserver 를 이용해 파일 업로드 기능을 만들다가 남겨놓으면 좋을거 같아 남깁니다.

 

코드는 아래 받으면 되고 Visual Studio 2017버전으로 작성이 되었습니다.

 

DotNetCoreFileUpload.zip
1.54MB

 

기본적인 코드를 소개(?)하겠습니다.

 

1. web server project create

   1.1 Controllers folder - new controller 

   1.2 Code

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.IO;

namespace WebServer.Controllers
{
    [ApiController]
    public class FIleUploadController : ControllerBase
    {
        [HttpPost]
        [Route("api/fileuload")]
        public ActionResult FileUpload([FromForm]FileUploadModel std)
        {
            // Getting Name
            string name = std.Name;
            // Getting Image
            var image = std.File;
            // Saving Image on Server
            if (image.Length > 0)
            {
                using (var fileStream = new FileStream(image.FileName, FileMode.Create))
                {
                    image.CopyTo(fileStream);
                }
            }

            return Ok(new { status = true, message = "Student Posted Successfully" });
        }
    }

    public class FileUploadModel
    {
        public string Name { get; set; }
        public IFormFile File { get; set; }
    }
}

2. windows forms project create

   2.1 Form1.cs Code(Ui는 첨부파일 참고)

using System;
using System.IO;
using System.Net.Http;
using System.Windows.Forms;

namespace WindowClient
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnFIleSelect_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog()
            {
                FileName = "Select a text file",
                Filter = "Text files (*.txt)|*.txt",
                Title = "Open text file",
                //InitialDirectory = 
                RestoreDirectory = true
            };

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                //Get the path of specified file
                tbxFile.Text = openFileDialog.FileName;

                //Read the contents of the file into a stream
                //var fileStream = openFileDialog.OpenFile();

                //using (StreamReader reader = new StreamReader(fileStream))
                //{
                //    fileContent = reader.ReadToEnd();
                //}
            }
        }

        private async void btnFileUpload_Click(object sender, EventArgs e)
        {
            byte[] fileBytes = null;
            try
            {
                using (FileStream fileStream = new System.IO.FileStream(tbxFile.Text, FileMode.Open))
                {
                    fileBytes = new byte[fileStream.Length];
                    fileStream.Read(fileBytes, 0, fileBytes.Length);
                    
                    HttpClient httpClient = new HttpClient();
                    MultipartFormDataContent form = new MultipartFormDataContent();

                    form.Add(new StringContent("John" /* value */), "Name" /* class member name */);
                    form.Add(new ByteArrayContent(fileBytes, 0, fileBytes.Length), "File" /* class member name */, "wwwFile" /* value(file name) */);
                    HttpResponseMessage response = await httpClient.PostAsync(tbxURL.Text, form);

                    if (response.IsSuccessStatusCode)
                    {
                        // process....
                    }
                }
            }
            catch (Exception ex)
            {
                // Exception ...
            }

        }
    }
}

테스트

1. WebServer 프로젝트 디버깅 시작 

2. WindowsClient 프로젝트 디버깅 시작 

 

참고 자료

https://dottutorials.net/dotnet-core-web-api-multipart-form-data-upload-file/

블로그 이미지

레몬도리 LemonDory

개발자의 이야기

댓글을 달아 주세요