问题描述
[AcceptVerbs(HttpVerbs.Post)]publicContentResultUpload(HttpPostedFileBaseFileData,stringfolder){stringfilename="";if(null!=FileData){try{filename=Path.GetFileName(FileData.FileName);//获得文件名stringfullPathname=Path.Combine(folder,filename);saveFile(FileData,folder,filename);}catch(Exceptionex){filename=ex.ToString();}}returnContent(filename);}[NonAction]privateboolsaveFile(HttpPostedFileBasepostedFile,stringfilepath,stringsaveName){boolresult=false;if(!Directory.Exists(filepath)){Directory.CreateDirectory(filepath);}try{postedFile.SaveAs(Path.Combine(filepath,saveName));result=true;}catch(Exceptione){thrownewApplicationException(e.Message);}returnresult;}
解决方案
解决方案二:
第一步:转换为byte数组byte[]fileData=newbyte[postedFile.ContentLength];postedFile.InputStream.Read(fileData,0,postedFile.ContentLength);第二步:入库如下sqlserver示例stringsql="insertintot_img(img)values(@img)";stringstrconn=System.Configuration.ConfigurationManager.ConnectionStrings["DB"].ToString();SqlConnectionsqlConn=newSqlConnection(strconn);SqlCommandsqlComm=newSqlCommand(sql,sqlConn);sqlComm.Parameters.Add("@img",SqlDbType.Image);sqlComm.Parameters["@img"].Value=fileData;sqlConn.Open();sqlComm.ExecuteNonQuery();sqlConn.Close();
解决方案三:
参考这里,把文件转换为数据流:
解决方案四:
将图片以二进制方式存储到数据库protectedvoidimgbtnCreate_Click(objectsender,ImageClickEventArgse){stringPerHomeName=tbPerHomeName.Text;//获取空间名stringPerHomeSign=txtPerSign.Text;//获取个性签名stringimgPath=uploadFile.PostedFile.FileName;//获取文件件名stringlastName=imgPath.Substring(imgPath.LastIndexOf(".")+1);//获取文件上传后缀名SqlConnectionconn=newSqlConnection(ConfigurationManager.AppSettings["conStr"]);conn.Open();if(uploadFile.PostedFile.FileName!=""&&lastName.ToLower()=="jpg"||lastName.ToLower()=="gif"){if(uploadFile.PostedFile.ContentLength>40960){Response.Write("<scriptlanguage='javaScript'>alert('你上传的图片超过了40KB!')</script>");return;}//codego.net/tags/11/1/intimgLength=uploadFile.PostedFile.ContentLength;//获取上传文件大小Byte[]imageData=newByte[imgLength];//定义Byte数组HttpPostedFilehp=uploadFile.PostedFile;//创建访问客户端上传文件的对象Streamimagestream=hp.InputStream;//创建数据流对象//将图片数据放到image数据对象实例中,其中0代表数组指针的起始位置,imagelength表示要读取流的长度imagestream.Read(imageData,0,imgLength);stringsqlstr="insertintoPerHomeDetail(PerHomeName,PerHomeSign,PerHomeLogo)values('"+PerHomeName+"','"+PerHomeSign+"',@ImageData)";SqlCommandcomm=newSqlCommand(sqlstr,conn);comm.Parameters.Add("@ImageData",SqlDbType.Image);comm.Parameters["@ImageData"].Value=imageData;comm.ExecuteNonQuery();conn.Close();Response.Write("<Script>alert('个人空间创建成功!')</Script>");}else{Response.Write("<script>alert('上传图像不能为空,且格式必须为gif或jpg!');location='javascript:history.go(-1)'</script>");}}