读书人

下面的代码怎样改才能获得要上传的文

发布时间: 2012-03-21 13:33:14 作者: rapoo

下面的代码怎样改,才能获得要上传的文件的实际路径呢?
各位朋友,问题如题 ,请赐教,谢谢!!!
string name = FileUpload1.FileName;//获取要上传的名字
string size = FileUpload1.PostedFile.ContentLength.ToString();//获取要上传文件的大小

string type = FileUpload1.PostedFile.ContentType
string type2 = name.Substring(name.LastIndexOf(".") + 1);//得到文件名的后缀名
string ipath = Server.MapPath("upimg") + @"\" + name;//获取文件上传的实际路径
string fpath = Server.MapPath("upfile") + @"\" + name;//获取文件上传的实际路径
string wpath ="upimg"+ @"\" + name; //写入到数据库去的虚拟路径



[解决办法]
看看微软自己给的例子吧:

C# code
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);

读书人网 >C#

热点推荐