.net上传图片并转成二进制流

时间:2021-08-27 09:29:09

话不多说,直接上代码

 <input id="InputFile" style="width: 399px" type="file" runat="server" />
<asp:Button ID="Button1" runat="server" Text="保存" onclick="Button1_Click" />
<asp:label ID="Label1" runat="server" text="Label"></asp:label>
<asp:Image ID="Image1" runat="server" />
 protected void Button1_Click(object sender, EventArgs e)
{
string fileName = InputFile.PostedFile.FileName;
Boolean fileOK = false; if (!string.IsNullOrWhiteSpace(fileName))
{
//判断上传文件的扩展名是否为允许的扩展名".gif", ".png", ".jpeg", ".jpg" ,".bmp"
String fileExtension = System.IO.Path.GetExtension(fileName).ToLower();
String[] Extensions = { ".gif", ".png", ".jpeg", ".jpg", ".bmp" };
for (int i = ; i < Extensions.Length; i++)
{
if (fileExtension == Extensions[i])
{
fileOK = true;
}
}
}
//如果上传文件扩展名为允许的扩展名,则将文件保存在服务器上指定的目录中
if (fileOK)
{
try
{
HttpPostedFile upFile = InputFile.PostedFile;//HttpPostedFile对象,用来读取上传图片的属性
int fileLength = upFile.ContentLength;//记录文件的长度
byte[] fileBytePicture = new byte[fileLength];//用图片的长度来初始化一个字节数组存储临时的图片文件
Stream fileStream = upFile.InputStream;//建立文件流对象
fileStream.Read(fileBytePicture, , fileLength);
string filetext = Convert.ToBase64String(fileBytePicture);
Label1.Text = filetext;
}
catch (Exception ex)
{
MessageBox("文件不能上传,原因:" + ex.Message); }
}
else
{
MessageBox("不能上传这种类型的文件");
}
}
protected void MessageBox(string str)
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "message", "<script language='javascript' defer>alert('" + str + "');</script>");
}