반응형
HttpPostedFileBase를 바이트로 변환 []
내 MVC 응용 프로그램에서 다음 코드를 사용하여 파일을 업로드하고 있습니다.
모델
public HttpPostedFileBase File { get; set; }
전망
@Html.TextBoxFor(m => m.File, new { type = "file" })
모든 것이 잘 작동합니다 .. 그러나 결과 fiel을 byte []로 변환하려고합니다. 어떻게해야합니까?
제어 장치
public ActionResult ManagePhotos(ManagePhotos model)
{
if (ModelState.IsValid)
{
byte[] image = model.File; //Its not working .How can convert this to byte array
}
}
Darin이 말했듯이 입력 스트림에서 읽을 수는 있지만 한 번에 사용 가능한 모든 데이터에 의존하지는 않습니다. .NET 4를 사용하는 경우 간단합니다.
MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();
CopyTo
원하는 경우 .NET 3.5 와 동등한 내용을 작성하는 것이 쉽습니다 . 중요한 부분은에서 읽는 것 HttpPostedFileBase.InputStream
입니다.
효율적인 목적으로 반환 된 스트림이 이미 다음인지 확인할 수 있습니다 MemoryStream
.
byte[] data;
using (Stream inputStream = model.File.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if (memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
입력 스트림에서 읽을 수 있습니다.
public ActionResult ManagePhotos(ManagePhotos model)
{
if (ModelState.IsValid)
{
byte[] image = new byte[model.File.ContentLength];
model.File.InputStream.Read(image, 0, image.Length);
// TODO: Do something with the byte array here
}
...
}
And if you intend to directly save the file to the disk you could use the model.File.SaveAs
method. You might find the following blog post useful.
참고URL : https://stackoverflow.com/questions/7852102/convert-httppostedfilebase-to-byte
반응형
'IT story' 카테고리의 다른 글
약속을 위해 루프를 작성하는 올바른 방법. (0) | 2020.07.25 |
---|---|
부트 스트랩 날짜 선택기-월과 년만 (0) | 2020.07.25 |
현재 분기가 아닌 분기로 'git pull'하는 방법은 무엇입니까? (0) | 2020.07.25 |
homebrew를 사용하여 macOS에서 이전 버전의 Python 3을 어떻게 설치할 수 있습니까? (0) | 2020.07.25 |
iOS의 UITableView에서 확장 / 축소 섹션 (0) | 2020.07.25 |