上传
protected void btnUpload_Click(object sender, EventArgs e) { if (!filUpload.HasFile) { Alert("没有上传文件"); return; } string sReg = @"\.jpg|\.jpeg|\.png"; if (!Regex.IsMatch(filUpload.FileName, sReg,RegexOptions.IgnoreCase)) { Alert("只接受jpg或png格式图片"); return; } int fileSize = filUpload.PostedFile.ContentLength; if (fileSize <= 0) { Alert("上传文件失败"); return; } int k = fileSize / 1024; if (k > 300) { Alert("文件太大"); return; } string fileType = filUpload.PostedFile.ContentType; string fileName = Path.GetFileName(filUpload.PostedFile.FileName); Byte[] fileByteArray; try { //图象文件临时储存Byte数组 fileByteArray = new Byte[fileSize]; //建立数据流对像 Stream StreamObject = filUpload.PostedFile.InputStream; //读取图象文件数据,fileByteArray为数据储存体,0为数据指针位置、fileSize为数据长度 StreamObject.Read(fileByteArray,0,fileSize); } catch { Alert("文件上传失败"); return; } SqlParameter[] sqlParas = new SqlParameter[5]; sqlParas[0] = new SqlParameter("@tpAppId", TpAppId); sqlParas[1] = new SqlParameter("@AttachmentName", fileName); sqlParas[2] = new SqlParameter("@Attachment", fileByteArray); sqlParas[3] = new SqlParameter("@AttachmentSize", k); sqlParas[4] = new SqlParameter("@AttachmentContentType", fileType); SQLHelper.DBHelper.ExecuteNonQuery(CommandType.StoredProcedure, "tp_prd_Upload", sqlParas); }
//显示
protected void Page_Load(object sender, EventArgs e) { SqlParameter[] sqlParas = new SqlParameter[1]; sqlParas[0] = new SqlParameter("@Id", Convert.ToInt32(Request.QueryString["TpId"])); DataTable dt = SQLHelper.DBHelper.ExecuteDataTable(CommandType.StoredProcedure, "tp_prd_ShowUpload", sqlParas); if (dt.Rows.Count == 0) return; DataRow dr = dt.Rows[0]; Response.Clear(); //设定输出文件类型 Response.ContentType = dr["AttachmentContentType"].ToString(); //Response.AddHeader("Content-Disposition", "attachment;filename=" + dr["AttachmentName"].ToString() + ";"); //输出图象文件二进制数制 Response.BinaryWrite((byte[])dr["Attachment"]); Response.Flush(); Response.End(); }