IT story

HttpPostedFileBase를 바이트로 변환 []

hot-time 2020. 7. 25. 10:25
반응형

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

반응형