读书人

封存图片

发布时间: 2013-11-05 14:40:42 作者: rapoo

保存图片
选择图片并上传,保存在指定文件夹下,图片名为 图片名+创建时间。
文件夹按月(或者星期)创建。
求代码 图片 .net保存图片
[解决办法]
前台:

   <asp:FileUpload ID="FileUpload_Upload" runat="server" CssClass="textbox" />
 <asp:Button ID="Button_Uploadfile" runat="server"
Text="Upload" CssClass="textbox" style="cursor:hand"
onclick="Button_Uploadfile_Click" />

后台:

//没文件夹创建文件夹
public void FolderPath(string pathStr)
{
if (!Directory.Exists(pathStr))
{
Directory.CreateDirectory(pathStr);
}
}
//按钮触发
protected void Button_Uploadfile_Click(object sender, EventArgs e)
{
string ServerPath = System.Web.HttpContext.Current.Request.MapPath("upload/"+DateTime.Now.ToString("yyyyMMdd"));
if (!string.IsNullOrEmpty(this.FileUpload_Upload.PostedFile.FileName))
{
FolderPath(ServerPath);
string Sion = Path.GetExtension(this.FileUpload_Upload.FileName);
string file = Path.GetFileNameWithoutExtension(this.FileUpload_Upload.FileName);


string FileName =file+ DateTime.Now.ToString("yyyyMMddHHmmssFFFFF")+Sion;
this.FileUpload_Upload.PostedFile.SaveAs(ServerPath + "/" + FileName );
//Alert("Upload success");

}
else {
//Alert("Please Select File To Upload!");
}
}








[解决办法]
string usename = users[0].CUserName.ToString(); //获取用户名
string randomName = DateTime.Now.ToFileTime().ToString(); //系统当前时间为图片名称
//string path = Request.MapPath("~/Content/images");
HttpPostedFileBase file = Request.Files["fileToUpload"];//获取页面上获取图片内容["fileToUpload"] 是页面上上传图片空间的name
string pictureName = file.FileName;//上传图片的原名
string extensionName = System.IO.Path.GetExtension(pictureName);//获取扩展名
int randomcode = BaseRandom.GetRandom(1000, 9999); //产生随机数
string newName = string.IsNullOrEmpty(pictureName.Trim()) ? "" : usename + randomcode + randomName + System.IO.Path.GetExtension(pictureName); //重命名图片
string savePath = HttpContext.Server.MapPath("~/Content/Uploads/img/" + usename); //原图图片保存位置
if (!System.IO.Directory.Exists(savePath))
{
//如果路径不存在创建新文件夹
System.IO.Directory.CreateDirectory(savePath);


}
file.SaveAs(savePath +'/'+newName); //将上传的文件保存到指定的目录。
ViewData["messageBox"] = "上传成功";


ps:这算是很完整的了

读书人网 >asp.net

热点推荐