SaveAs方法配置为需要根路径,路径'fp'不是root

11 .net c# file

我正在Asp.net中进行Image uploader,我在我的控件下面给出了以下代码:

    string st;
    st = tt.PostedFile.FileName;
    Int32 a;
    a = st.LastIndexOf("\\");
    string fn;
    fn = st.Substring(a + 1);
    string fp;
    fp = Server.MapPath(" ");
    fp = fp + "\\";
    fp = fp + fn;
    tt.PostedFile.SaveAs("fp");
Run Code Online (Sandbox Code Playgroud)

但在上传或保存图像期间,出现错误消息:SaveAs方法配置为需要根路径,并且路径'fp'不是root. 所以请帮帮我解决问题

Jon*_*eet 27

我怀疑问题是你使用字符串"fp"而不是变量fp.这是固定代码,也使(IMO)更具可读性:

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

您还应该考虑将倒数第二行更改为:

string fullPath = Path.Combine(Server.MapPath(" "), trailingPath);
Run Code Online (Sandbox Code Playgroud)

您可能还想考虑如果发布的文件在文件名中使用/而不是\来会发生什么...例如,如果它是从Linux发布的.实际上,您可以将前三行的全部内容更改为:

string trailingPath = Path.GetFileName(tt.PostedFile.FileName));
Run Code Online (Sandbox Code Playgroud)

结合这些,我们得到:

string trailingPath = Path.GetFileName(tt.PostedFile.FileName));
string fullPath = Path.Combine(Server.MapPath(" "), trailingPath);
tt.PostedFile.SaveAs(fullPath);
Run Code Online (Sandbox Code Playgroud)

更清洁,IMO :)


Maj*_*jid 6

使用Server.MapPath()

fileUploader.SaveAs(Server.MapPath("~/Images/")+"file.jpg");
Run Code Online (Sandbox Code Playgroud)