본문 바로가기
coding/React

React + C# .NET 사용하여 파일 업로드(File Upload ) 하기

by 김학준0724 2022. 9. 6.

React 와 .NET로 파일을 업로드 방법을 정리하려고합니다.

간단한 방법은 아래와 같습니다.

 

클라이언트 앱(react)

  1. view 페이지에서 input[type=file] 요소를 적절한 위치에 추가.
  2. state 추가( state를 이용해서 파일을 업로드하려고합니다.)
  3. input[type=file] 이벤트 처리 추가
  4. submit 버튼 클릭 시 서버 호출 코드 추가

서버 앱(.net)

  1. fileupload 함수 작성
 
1) 클라이언트 앱(react)

useState( file , setFile) = useState()

    const onChange_Attached = (e) => {
            setFile(e.target.files[0] )
    }    

    const onSubmt_Next = (e) => {

        const form = new FormData();
        form.append("files" , file , file.name)

        const data = await(await (fetch(`${getServerAddress()}/api/tpainfo/uploadToServer`, {method: 'post', body: form}))).json();
    )

	return(
    <>
        <div>
            <input type="file" onChange={onChange_Attached} >Attached</input>
        </div>              

        <form onSubmit={onSubmt_Next}>
            <button type="submit">Next</button>
        </form>
	</>
    )

 

2) 서버 앱(.net)
        [HttpPost("FromForm")]
        [Route("upload")]
        public async Task<SortedList> UploadToLocal(IFormFile files)
        {
            try
            {
                SortedList result = new SortedList();
                string dirPath = @"C:\Temp\FIleUpload";
                if (files.Name != "")
                {
                    if (!Directory.Exists(dirPath))
                    {
                        dirPath = @"D:\Temp\FIleUpload";
                    }

                    if (!Directory.Exists(dirPath))
                    {
                        Directory.CreateDirectory(dirPath);

                        if(!System.IO.File.Exists(dirPath + @"\" + files.FileName))
                        {
                            using (var stream = System.IO.File.Create(dirPath + @"\" +files.FileName))
                            {
                                await files.CopyToAsync(stream);
                            }

                            result.Add("msg", "success:");
                            return result;
                        }
                    }

                    result.Add("msg", "Fail:");
                    return result;
                }
                else {
                    result.Add("msg", "Fail:");
                    return result;
                }
            }
            catch (Exception ex)
            {
                SortedList result = new SortedList();
                result.Add("msg", "Fail: " + ex.Message);
                return result;
            }
        }
 

3) 구현 결과