繁体   English   中英

如何以二进制格式保存图像?

[英]How to save the image in binary format?

我已将所选文件附加到formData中,并使用XML请求发送到服务器端。 在服务器端,我需要以二进制格式保存接收的文件。

我现有的代码是

var httpPostedFile = System.Web.HttpContext.Current.Request.Files["MyFiles"];

var fileSave = System.Web.HttpContext.Current.Server.MapPath("SavedFiles");

Directory.CreateDirectory(fileSave);

var fileSavePath = Path.Combine(fileSave, httpPostedFile.FileName);

到此为止,已创建一个文件夹。 我不知道如何在创建的位置将文件保存为二进制格式。

盲目地我在下面尝试过

FileStream fs = System.IO.File.Create(fileSavePath);
byte[] b;
using (BinaryReader br = new BinaryReader(fs))
{
   b = br.ReadBytes((int)fs.Length);                         
}
using (BinaryWriter bw = new BinaryWriter(fs))
{
bw.Write(b);
}

但它引发了异常。 你可以在这里建议如何实现我的需求吗?

要保存已发布的文件,假设httpPostedFile不为null,您只需使用SaveAs(...)

HttpPostedFile httpPostedFile = ...

// I've changed your method to use Path.GetFileName(...) to ensure that there are no path elements in the input filename.
var fileSavePath = Path.Combine(fileSave, Path.GetFileName(httpPostedFile.FileName));
httpPostedFile.SaveAs(fileSavePath);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM