foreach on Request.Files
ASP.NET MVC에서 여러 파일을 업로드하려고하는데 컨트롤러에이 간단한 foreach 루프가 있습니다.
foreach (HttpPostedFileBase f in Request.Files)
{
if (f.ContentLength > 0)
FileUpload(f);
}
이전 코드는 다음 오류를 생성합니다.
Unable to cast object of type 'System.String' to type 'System.Web.HttpPostedFile'.
내가 이해하지 못하는 것은 Request.Files [1]이 HttpPostedFileBase를 반환하는 이유이지만 반복 될 때 문자열 (아마도 파일 이름)을 반환합니다.
참고 :이 문제는 for 루프로 해결할 수 있다는 것을 알고 있습니다. 또한 동일한 오류로 HttpPostedFile을 사용해 보았습니다.
의 열거 HttpFileCollection
자는 HttpPostedFileBase
개체가 아닌 파일의 키 (이름)를 반환 합니다. 키를 받으면 키 (파일 이름)와 함께 Item
( []
) 속성을 사용 하여 HttpPostedFileBase
객체 를 가져옵니다 .
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
...
}
내 탭 HTML은 다음과 같습니다.
<input class="valid" id="file" name="file" multiple="" type="file">
Request.Files는 배열에서 중복 된 이름을 갖습니다. 따라서 다음과 같이 해결해야합니다.
for (int i = 0; i < Request.Files.Count; i++ ){
HttpPostedFileBase fileUpload = Request.Files[i];
LINQ를 사용하여이 작업을 수행하고 요청에 따라 foreach를 계속 사용할 수 있습니다.
var files = Enumerable.Range(0, Request.Files.Count)
.Select(i => Request.Files[i]);
foreach (var file in files)
{
// file.FileName
}
@tvanfosson이 말했듯이 열거자는 파일 이름을 HttpPostedFileBase
. 이 메서드 HttpPostedFileBase this[string name]
는 우리가 원하는 객체를 반환합니다. 경우 HttpFileCollectionBase
구현 IEnumerable<HttpPostedFileBase>
우리는 일반적으로 foreach 문을 수행 할 수 있습니다. 그러나 비 제네릭 IEnumerable
.
다음과 같이 문자열을 반복하고 대신 HttpPostedFile로 캐스팅 해 볼 수 있습니다.
foreach (string file in Request.Files)
{
HttpPostedFile hFile = Request.Files[file] as HttpPostedFile;
if (hFile.ContentLength > 0)
FileUpload(hFile);
}
불행히도 tvanfosson의 대답은 저에게 효과가 없었습니다. 파일이 정상적으로 업로드되고 오류가 발생하지 않더라도 파일 중 하나만 사용되는 문제가 발생하므로 두 파일을 모두 사용하지 않고 동일한 파일이 두 번 저장됩니다.
Request.Files의 각 파일 이름을 반복하는 foreach 문에 문제가있는 것 같았습니다. 어떤 이유로 든 키로 작동하지 않고 매번 첫 번째 파일 만 선택됩니다.
HttpFileCollectionBase files = Request.Files;
for(var i = 0; i < files.Count; i++)
{
HttpPostedFileBase file = files[i];
...
}
The following code worked for me.
HttpResponseMessage result = null;
var httpRequest = System.Web.HttpContext.Current.Request;
HttpFileCollection uploadFiles = httpRequest.Files;
var docfiles = new List<string>();
if (httpRequest.Files.Count > 0){
int i;
for (i = 0; i < uploadFiles.Count; i++) {
HttpPostedFile postedFile = uploadFiles[i];
var filePath = @"C:/inetpub/wwwroot/test1/reports/" + postedFile.FileName;
postedFile.SaveAs(filePath);
docfiles.Add(filePath);
}
result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
} else {
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
You can get the HttpPostedFile
out of the HttpFileCollection
using foreach
like this:
foreach (var obj in fileCollection)
{
HttpPostedFile file = fileCollection.Get(obj.ToString());
}
참고URL : https://stackoverflow.com/questions/1760510/foreach-on-request-files
'Program Tip' 카테고리의 다른 글
Nodemon-파일 제외 (0) | 2020.11.13 |
---|---|
Hibernate, iBatis, Java EE 또는 기타 Java ORM 도구 (0) | 2020.11.13 |
Python의 파일에서 한 번에 한 문자를 읽는 방법은 무엇입니까? (0) | 2020.11.13 |
IF a == true OR b == true 문 (0) | 2020.11.13 |
MySQL에서`REPLACE`와`INSERT… ON DUPLICATE KEY UPDATE`의 실질적인 차이점은 무엇입니까? (0) | 2020.11.13 |