日期:2014-05-18 浏览次数:20836 次
protected void Page_Load(object sender, EventArgs e) { if(IsPostBack) { Boolean fileOK = false; String path = Server.MapPath("~/UploadedImages/"); if (FileUpload1.HasFile) { String fileExtension = System.IO.Path.GetExtension(FileUpload1.FileName).ToLower(); String[] allowedExtensions = {".gif", ".png", ".jpeg", ".jpg"}; for (int i = 0; i < allowedExtensions.Length; i++) { if (fileExtension == allowedExtensions[i]) { fileOK = true; } } } if (fileOK) { try { FileUpload1.PostedFile.SaveAs(path + FileUpload1.FileName); Label1.Text = "File uploaded!"; } catch (Exception ex) { Label1.Text = "File could not be uploaded."; } } else { Label1.Text = "Cannot accept files of this type."; } } }
------解决方案--------------------
提示:把获取文件路径写在一个方法中,上传和读取文件的路径时调用这个方法就可以。。
public static string GetUploadFilePath(Channels channel, string fileName, string extend, bool isUpload)
{
............
string folder = fileName.Substring(0, 1);
string directory = string.Format("{0}Img\\{1}\\{2}", HttpContext.Current.Request.MapPath("/"), channelPath, folder);
if (!Directory.Exists(directory))
Directory.CreateDirectory(directory);
if (isUpload)
fullPath = string.Format("{0}\\{1}{2}", directory, fileName, extend);
else
fullPath = string.Format("/Img/{0}/{1}/{2}{3}", channelPath, folder, fileName, fullExtend);
return fullPath;
}
在其它地方调用这个方法即可。。。
string path=GetUploadFilePath(Channels channel, string fileName, string extend, bool isUpload);