<body> <form > 四张图片的文件名为pic1,pic2,pic3,pic4 我上传的图片需要改成其中一张, 思路是先通过上传到服务器这些图片所在的文件夹IMAGE中,然后再修改文件名。 修改文件名的思路是先COPY在删除源文件。 后台代码如下:先要引用SYSTEM.IO
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { imagebind(); }
} private void imagebind() { Image1.ImageUrl = "image/pic1.jpg"; Image2.ImageUrl = "image/pic2.jpg"; Image3.ImageUrl = "image/pic3.jpg"; Image4.ImageUrl = "image/pic4.jpg"; } protected void Button1_Click(object sender, EventArgs e) { tihuan(FileUpload1, "pic1.jpg"); } protected void Button3_Click(object sender, EventArgs e) { tihuan(FileUpload2, "pic2.jpg"); } protected void Button4_Click(object sender, EventArgs e) { tihuan(FileUpload3, "pic3.jpg"); } protected void Button5_Click(object sender, EventArgs e) { tihuan(FileUpload4, "pic4.jpg"); } private void tihuan(FileUpload myFileUpload,string newname) { bool b = Upload(myFileUpload); // if (!b) { return; } string OrignFile, NewFile; OrignFile = Server.MapPath(".") + "\\image\\"+myFileUpload.FileName; NewFile = Server.MapPath(".") + "\\image\\"+newname; File.Copy(OrignFile, NewFile, true); File.Delete(OrignFile); } private bool Upload(FileUpload myFileUpload) { bool flag = false; //是否允许上载 bool fileAllow = false; //设定允许上载的扩展文件名类型 string[] allowExtensions = { ".jpeg", ".gif", ".bmp", ".png", ".jpg", ".tiff" };
//取得网站根目录路径 string path = HttpContext.Current.Request.MapPath("image/"); //检查是否有文件案 if (myFileUpload.HasFile) { //myFileUpload.FileName = "pic1111111.jpg"; //取得上传文件之扩展文件名,并转换成小写字母 string fileExtension = System.IO.Path.GetExtension(myFileUpload.FileName).ToLower(); //检查扩展文件名是否符合限定类型 for (int i = 0; i < allowExtensions.Length; i++) { if (fileExtension == allowExtensions[i]) { fileAllow = true; } }
if (fileAllow) { try { //存储文件到文件夹 myFileUpload.SaveAs(path + myFileUpload.FileName); flag = true; } catch (Exception ex) { PubClass.ShowMessageBox(Page, ex.Message); flag = false; } } else { PubClass.ShowMessageBox(Page, "不允许上载:" + myFileUpload.PostedFile.FileName + ",只能上传图片文件,请检查!");
flag = false; } } else { PubClass.ShowMessageBox(Page, "请选择要上传的图片文件!"); flag = false; } return flag; }
最关键的语言: string OrignFile, NewFile; OrignFile = Server.MapPath(".") + "\\image\\"+myFileUpload.FileName; NewFile = Server.MapPath(".") + "\\image\\"+newname; File.Copy(OrignFile, NewFile, true); File.Delete(OrignFile); 代码很简单,想法也很清楚。 请高手给给更简单的方式实现文件上传并修改文件名。谢谢
|
请发表评论