HttpPostedFileBase를 byte []로 변환


123

내 MVC 응용 프로그램에서 다음 코드를 사용하여 파일을 업로드하고 있습니다.

모델

 public HttpPostedFileBase File { get; set; }

전망

@Html.TextBoxFor(m => m.File, new { type = "file" })

모든 것이 잘 작동합니다 ..하지만 결과 파일을 byte []로 변환하려고합니다. 어떻게해야합니까?

제어 장치

 public ActionResult ManagePhotos(ManagePhotos model)
    {
        if (ModelState.IsValid)
        {
            byte[] image = model.File; //Its not working .How can convert this to byte array
        }
     }

답변:


259

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();
}

첫 번째 예제는 .NET4에서 작동하지 않았습니다 (다른 예제는 시도하지 않았 음)-.png 또는 .jpg로 시도했을 때는 작동하지 않았지만 .txt 파일을 사용하면 작동했습니다. . 이유를
— 아는

2
@VoodooChild : 아마도 뭔가 당신이 텍스트로 데이터를 취급하고 무슨 일을하는지있다. 그래도 알기 위해 더 많은 코드를 볼 필요가 있습니다. 전체 시나리오를 제공하는 다른 질문을하는 것이 좋습니다.
— Jon Skeet 2011

6
좋아, 이것은 약간의 맥락을 제공하기 위해 나를 위해 일했습니다-감사합니다! `이미지 img = Image.FromStream (file.InputStream); MemoryStream ms = 새로운 MemoryStream (); img.Save (ms, ImageFormat.Jpeg); model.SiteLogo = ms.ToArray ();`
— VoodooChild 2011

7
나는 inputstream 위치가 스트림의 끝에 있다는 것을 발견했고, 그래서 model.File.InputStream.Position = 0;그것을 작동시키기 위해 Jon의 코드 앞에 줄을 추가 해야했다
— Manish

2
@UweKeim : 예, 이미 using 문 (지시문, btw가 아님)이 inputStream있으며 둘 다 동일한 객체를 참조합니다. 왜 두 번 폐기하겠습니까?
— Jon Skeet

27

입력 스트림에서 읽을 수 있습니다.

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
    }
    ...
}

파일을 디스크에 직접 저장하려면 model.File.SaveAs방법을 사용할 수 있습니다 . 다음 블로그 게시물이 유용 할 수 있습니다 .


5
HttpPostedFileBase에 대한 InputStream은 Read에 대한 단일 호출로 모든 데이터를 반환하도록 보장 됩니까? 가능한 경우이를 피하는 것이 가장 좋습니다.
— Jon Skeet
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.