일부 기능을 입증하기 위해 테스트 앱을 작업 중이며, 제출하려는 사용자가 양식을 작성하면 양식의 모든 값이 포함 된 JSON 파일이 다운로드됩니다. 거기에서 사용자는 해당 파일을 가져 와서 원래 사용자의 선택 사항을 유지하면서 양식에 대한 추가 정보를 작성하는 데 사용할 다른 당사자에게 해당 JSON 파일을 보냅니다.
여기 내가 지금까지 얻은 것입니다.
데이터 모델
public class TableDemo
{
public List<Location> Locations { get; set; }
public List<User> Users { get; set; }
public TableDemo()
{
Locations = new List<Location>();
Locations.Add(new Location());
Users = new List<User>();
Users.Add(new User());
}
}
public class Location
{
[Required]
public string Street { get; set; }
[Required]
public string City { get; set; }
[Required]
public string State { get; set; }
[Required]
public string Zip { get; set; }
}
public class User
{
public string FirstName { get; set; }
public string LastName { get; set; }
public string PhoneNumber { get; set; }
}
제어 장치
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
TableDemo model = new TableDemo();
return View(model);
}
// This is where the user fills out the original form which downloads to their machine as a JSON file.
[HttpPost]
public IActionResult Index(TableDemo model)
{
string jsonString;
var options = new JsonSerializerOptions
{
WriteIndented = true
};
jsonString = JsonSerializer.Serialize(model, options);
byte[] jsonFileArray = Encoding.ASCII.GetBytes(jsonString);
return File(jsonFileArray, "application/json", "testJson.json");
}
// Where the second user inputs the file from the first user
[HttpGet]
public IActionResult ImportForm()
{
return View();
}
// the jsonString argument is always null here
[HttpPost]
public IActionResult ImportForm(string jsonString)
{
TableDemo model = JsonSerializer.Deserialize<TableDemo>(jsonString);
return View("IndexDeserialized", model);
}
}
보기 (ImportForm.cshtml)
@section Scripts{
<script>
function showFile(input) {
let file = input.files[0];
let reader = new FileReader();
reader.readAsText(file);
reader.onload = () => {
console.log(reader.result);
let jsonContent = $('#jsonContent');
jsonContent.append(reader.result);
};
reader.onerror = function () {
console.log(reader.error);
};
};
</script>
}
<body>
<form name="form" method="post" enctype="multipart/form-data">
<div class="form-group">
<input type="file" class="form-control" name="file" onchange="readDocument(this)" />
</div>
<div id="jsonContent">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</form>
</body>
초기보기에서 생성 된 내 JSON 파일의 내용
{
"Locations": [
{
"Street": "12345 Test Drive",
"City": "Chicago",
"State": "IL",
"Zip": "55555"
},
{
"Street": "12345 Test Drive",
"City": "ABC",
"State": "IL",
"Zip": "60441"
},
{
"Street": "1234",
"City": "asdasd",
"State": "asdasd",
"Zip": "asdasd"
}
],
"Users": [
{
"FirstName": "asdas",
"LastName": "dasdsa",
"PhoneNumber": "dasd"
},
{
"FirstName": "sadasd",
"LastName": "dsadas",
"PhoneNumber": "asdasd"
}
]
}
그래서 여기에서 나는 조금 길을 잃었습니다. 파일을 제출하고 JSON 문자열에 대한 해당 HttpPost
작업을 ImportForm
수행하거나 메모리에 가져 오면 전체 파일을 deserialize 하도록 제출하는 몇 가지 방법을 시도했습니다 .string
IFormFile
파일을 어디에도 보관하고 싶지 않고 파일에서 직접 실제 JSON 텍스트를 가져 와서 다시 TableDemo
개체 로 역 직렬화 하고 값이 채워진 새 페이지로 이동하려고 시도했지만 모든 시도는 막 다른 골목으로 이어집니다 파일 경로가 필요하거나 (이 파일을 어디에도 저장하고 싶지 않음) 컨트롤러 작업에 JSON 문자열을 보내려고 할 때 null 개체가 발생합니다.
어떻게 간단히 JSON 파일의 내용을 가져 와서 TableDemo
객체 로 역 직렬화 하고 그 값을 새 페이지에 표시 할 수 있습니까?
좋아 여기에 내 대답이 있습니다. 나는 당신의 코드를 살펴 보았고 꽤 적은 문제가 있습니다. 내가 당신을 위해 모든 것을 고쳐야한다면 시간이 좀 걸릴 것입니다. 하지만 여기에 몇 가지 제안이 있으며 다음 단계로 넘어갈 수 있습니다.
멀티 파트 형식으로 파일을 업데이트하려고하지만 문자열을 가져 오려고합니다. 파일에 json 문자열이 포함되어 있지만 여전히 파일입니다. 그래서 우리는 그 부분을 처리해야합니다.
그래서 당신은 자바 스크립트와 뷰에서 데이터를 보여 주려고합니다. 내 예에서는 데이터를 표시하는 데 중점을 두 었으며 IndexDeserialized
JavaScript 부분은 다른 질문으로 남겨졌습니다.
내가 한 일과 제안 :
컨트롤러에서 다음 방법을 제거하고 게시 한 방법으로 바꿉니다.
[HttpPost]
public IActionResult ImportForm(string jsonString)
{
TableDemo model = JsonSerializer.Deserialize<TableDemo>(jsonString);
return View("IndexDeserialized", model);
}
새로운 방법은 업로드 한 파일을 읽고 그 결과를 동일한 페이지에 반환 할 수있는 간단한 예제입니다.
[HttpPost]
public async Task<IActionResult> ImportFormOnPost()
{
string jsonString = string.Empty;
if (HttpContext.Request.Form.Files[0] != null)
{
var file = HttpContext.Request.Form.Files[0];
await using (MemoryStream ms = new MemoryStream())
{
await file.CopyToAsync(ms);
jsonString = Encoding.UTF8.GetString(ms.ToArray());
}
}
TableDemo model = JsonSerializer.Deserialize<TableDemo>(jsonString);
return View("IndexDeserialized", model);
}
ImportForm에서 작업이 누락되었습니다.이 경우 ImportFormOnPost
메서드에 게시합니다 .
<form name="form" method="post" enctype="multipart/form-data" action="ImportFormOnPost">
<div class="form-group">
<input type="file" class="form-control" name="file" />
</div>
<div id="jsonContent">
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
<div style="margin-top:15px">
<output form="uploadForm" name="result"></output>
</div>
</form>
마지막으로 데이터를 IndexDeserialized
다음 위치에 표시합니다 .
@model FileUploaderApp.Models.TableDemo
<p>Number for locations: @Model?.Locations?.Count</p>
@if (Model != null)
{
foreach (var user in @Model.Users)
{
<p>@user.FirstName @user.LastName</p>
}
}
프론트 엔드에서 JavaScript를 사용하여 데이터를 JSON 객체로 표시하는 것이 가능하지만이 부분은 자체 질문이라고 생각합니다.
그리고 이것은 단지 예일뿐임을 기억하십시오. 그 위에 많은 것을 할 수 있습니다.
최종 결과는 다음과 같습니다.
내가 한 일에 대해 Microsoft에서 파일 업로드 에 대해 읽었습니다. 이 리소스 코드 파일 업로드 예제를 확인하십시오 .
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다