반응형
부탁한다.ASP 내의 파일네트워크 코어
ajax request를 사용하여 aspnet core를 사용하여 파일을 업로드하려고 합니다.이전 버전의 .net에서는 다음을 사용하여 이 문제를 처리했습니다.
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//Save file content goes here
fName = file.FileName;
(...)
하지만 지금은 요청 시 오류가 표시됩니다.files 어떻게 하면 작동합니까? 검색해보니 httpposted 파일이 iform file로 변경되었지만 요청을 처리하는 방법을 찾았습니다.파일?
이것은 최근 프로젝트의 작업 코드입니다.요청에서 데이터가 이동되었습니다.요청할 파일.Form.Files.스트림을 바이트 배열로 변환해야 하는 경우 - 이 구현이 유일하게 작동했습니다.다른 사용자는 빈 어레이를 반환합니다.
using System.IO;
var filePath = Path.GetTempFileName();
foreach (var formFile in Request.Form.Files)
{
if (formFile.Length > 0)
{
using (var inputStream = new FileStream(filePath, FileMode.Create))
{
// read file to stream
await formFile.CopyToAsync(inputStream);
// stream to byte array
byte[] array = new byte[inputStream.Length];
inputStream.Seek(0, SeekOrigin.Begin);
inputStream.Read(array, 0, array.Length);
// get file name
string fName = formFile.FileName;
}
}
}
제가 찾은 두 가지 좋은 솔루션에서 이 결합은 어떻습니까?
var myBytes = await GetByteArrayFromImageAsync(Request.Form.Files[0]);
private async Task<byte[]> GetByteArrayFromImageAsync(IFormFile file)
{
using (var target = new MemoryStream())
{
await file.CopyToAsync(target);
return target.ToArray();
}
}
이 코드는 일반 형식 또는 Ajax를 사용하여 업로드된 두 파일에 대해 100% 작동합니다.
[HttpPost]
public async Task<IActionResult> Upload(IList<IFormFile> files)
{
foreach (IFormFile source in files)
{
string filename = ContentDispositionHeaderValue.Parse(source.ContentDisposition).FileName.Trim('"');
filename = this.EnsureCorrectFilename(filename);
using (FileStream output = System.IO.File.Create(this.GetPathAndFilename(filename)))
await source.CopyToAsync(output);
}
return this.RedirectToAction("Index");
}
private string EnsureCorrectFilename(string filename)
{
if (filename.Contains("\\"))
filename = filename.Substring(filename.LastIndexOf("\\") + 1);
return filename;
}
private string GetPathAndFilename(string filename)
{
return this.HostingEnvironment.WebRootPath + "\\files\\" + filename;
}
언급URL : https://stackoverflow.com/questions/36661830/request-files-in-asp-net-core
반응형
'programing' 카테고리의 다른 글
함수 호출 후 괄호 2세트 (0) | 2023.03.26 |
---|---|
Angular에서 컨트롤러를 다른 컨트롤러에 주입하려면 어떻게 해야 합니까?JS (0) | 2023.03.26 |
재료 UI에서 텍스트 필드의 글꼴 크기를 변경할 수 없습니다. (0) | 2023.03.26 |
asp.net mvc에서 요청이 ajax인지 확인하는 방법 (0) | 2023.03.26 |
mongoose는 왜 항상 내 컬렉션 이름 끝에 s를 추가합니까? (0) | 2023.03.26 |