The SaveAs method is configured to require a rooted path, and the path 'fp' is not rooted

后端 未结 6 1251
有刺的猬
有刺的猬 2020-12-06 17:47

I am doing Image uploader in Asp.net and I am giving following code under my controls:

    string st;
    st = tt.PostedFile.FileName;
    Int32 a;
    a =          


        
6条回答
  •  失恋的感觉
    2020-12-06 18:06

    I suspect the problem is that you're using the string "fp" instead of the variable fp. Here's the fixed code, also made (IMO) more readable:

    string filename = tt.PostedFile.FileName;
    int lastSlash = filename.LastIndexOf("\\");
    string trailingPath = filename.Substring(lastSlash + 1);
    string fullPath = Server.MapPath(" ") + "\\" + trailingPath;
    tt.PostedFile.SaveAs(fullPath);
    

    You should also consider changing the penultimate line to:

    string fullPath = Path.Combine(Server.MapPath(" "), trailingPath);
    

    You might also want to consider what would happen if the posted file used / instead of \ in the filename... such as if it's being posted from Linux. In fact, you could change the whole of the first three lines to:

    string trailingPath = Path.GetFileName(tt.PostedFile.FileName));
    

    Combining these, we'd get:

    string trailingPath = Path.GetFileName(tt.PostedFile.FileName));
    string fullPath = Path.Combine(Server.MapPath(" "), trailingPath);
    tt.PostedFile.SaveAs(fullPath);
    

    Much cleaner, IMO :)

提交回复
热议问题