将HttpPostedFileBase进行base64编码

8

我想将接收到的HttpPostedFileBase图片进行base64编码,以便在json对象中发送,但是我不知道该如何实现...请告诉我如何解码回HttpPostedFileBase

3个回答

17

我尝试过这个方法,它有效。

string theFileName = Path.GetFileName(YourFile.FileName);
byte[] thePictureAsBytes = new byte[YourFile.ContentLength];
using (BinaryReader theReader = new BinaryReader(YourFile.InputStream))
{
    thePictureAsBytes = theReader.ReadBytes(YourFile.ContentLength);
}
string thePictureDataAsString = Convert.ToBase64String(thePictureAsBytes);

1
你在这里没有使用theFileName。 - SeanMC
@SeanKPS theFileName 可根据您的情况使用,例如在这里我将其用作 Web 服务的输入,该服务将把它存储在数据库中。 - Abdallah

1

按照以下步骤将 HttpPostedFileBase 转换为 Base64String 类型

  public ActionResult ParseCv(HttpPostedFileBase cvFile)
    {            
        byte[] fileInBytes = new byte[cvFile.ContentLength];
        using (BinaryReader theReader = new BinaryReader(cvFile.InputStream))
        {
            fileInBytes = theReader.ReadBytes(cvFile.ContentLength);
        }
        string fileAsString= Convert.ToBase64String(fileInBytes);
        return Content(fileAsString);
    }

0
你可以这样做:
byte[] binaryData;
  binaryData = new Byte[product.BrochureFile.InputStream.Length];
  long bytesRead = product.BrochureFile.InputStream.Read(binaryData, 0, (int)product.BrochureFile.InputStream.Length);
  product.BrochureFile.InputStream.Close();
  string base64String = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接