您好我使用此C#代码上传图片。
protected void UploadFile(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
byte[] bytes = br.ReadBytes((Int32)fs.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO foto(FileName, ContentType, Content) VALUES (@FileName, @ContentType, @Content)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@FileName", filename);
cmd.Parameters.AddWithValue("@ContentType", contentType);
cmd.Parameters.AddWithValue("@Content", bytes);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
我在longblob字段中上传图像,然后显示我正在使用C#WebService,AJAX,JavaScript的图像,将图像转换为Base64String,但图像显示为不存在。
这是我的Base64String:
正如您所看到的,问题在于这个额外的字符:
AAEAAAD/////AQAAAAAAAAAPAQAAAHgBAAAC
为什么会这样?我该如何解决?
答案 0 :(得分:0)
很长一段时间我回到了同样的问题,我记不起当时的事情:
我检查我是否错了:
http://jsfiddle.net/hpP45/
我首先尝试解码(谷歌bse64解码器)
https://www.base64decode.org/
并将解码后的二进制数据保存为jpeg文件并打开它。
如果它没有打开那么我想,你的base64编码可能有问题
答案 1 :(得分:0)
可以用上面的代码
替换下面的线条吗? protected void UploadFile(object sender, EventArgs e)
{
string filename = Path.GetFileName(FileUpload1.PostedFile.FileName);
string contentType = FileUpload1.PostedFile.ContentType;
using (Stream fs = FileUpload1.PostedFile.InputStream)
{
using (BinaryReader br = new BinaryReader(fs))
{
System.Drawing.Image imagetuUpload = System.Drawing.Image.FromStream(fs);
Bitmap bitmap = new Bitmap(imagetuUpload);
System.IO.MemoryStream stream = new MemoryStream();
bitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
stream.Position = 0;
byte[] upproimag = new byte[stream.Length + 1];
stream.Read(upproimag, 0, upproimag.Length);
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (MySqlConnection con = new MySqlConnection(constr))
{
string query = "INSERT INTO foto(FileName, ContentType, Content) VALUES (@FileName, @ContentType, @Content)";
using (MySqlCommand cmd = new MySqlCommand(query))
{
cmd.Connection = con;
cmd.Parameters.AddWithValue("@FileName", filename);
cmd.Parameters.AddWithValue("@ContentType", contentType);
cmd.Parameters.AddWithValue("@Content", upproimag);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
}
}
Response.Redirect(Request.Url.AbsoluteUri);
}
我跳,它可以帮助你:)