React 와 .NET로 파일을 업로드 방법을 정리하려고합니다.
간단한 방법은 아래와 같습니다.
클라이언트 앱(react)
- view 페이지에서 input[type=file] 요소를 적절한 위치에 추가.
- state 추가( state를 이용해서 파일을 업로드하려고합니다.)
- input[type=file] 이벤트 처리 추가
- submit 버튼 클릭 시 서버 호출 코드 추가
서버 앱(.net)
- 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) 구현 결과

'coding > React' 카테고리의 다른 글
| [React] input file 태그 내에서 value 값 설정하기 - Failed to set the 'value' property on 'HTMLInputElement (0) | 2022.09.26 |
|---|---|
| React + C# .NET + fetch 사용하여 파일 다운로드(File download) 하기 (0) | 2022.09.22 |