如何保存上传的文件?时间:2019-05-06 标签:c#mvc
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17944645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How save uploaded file? c# mvc
提问by
I want upload an image file to project's folder but I have an error in my catch: Could not find a part of the path 'C:\project\uploads\logotipos\11111\'.
我想将图像文件上传到项目的文件夹,但我的捕获出错:找不到路径“C:\project\uploads\logotipos\11111\”的一部分。
What am I do wrong? I want save that image uploaded by my client in that folder... that folder exists... ah if I put a breakpoint for folder_exists3 that shows me a true value!
我做错了什么?我想将我的客户端上传的图像保存在该文件夹中...该文件夹存在...啊,如果我为 folder_exists3 设置一个断点,显示我的真实值!
My code is:
我的代码是:
try
{
var fileName = dados.cod_cliente;
bool folder_exists = Directory.Exists(Server.MapPath("~/uploads"));
if(!folder_exists)
Directory.CreateDirectory(Server.MapPath("~/uploads"));
bool folder_exists2 = Directory.Exists(Server.MapPath("~/uploads/logo"));
if(!folder_exists2)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo"));
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/"));
}
catch(Exception e)
{
}
Someone knows what I'm do wrong?
有人知道我做错了什么吗?
Thank you :)
谢谢 :)
采纳答案by Jeyhun Rahimov
Try this:
尝试这个:
string targetFolder = HttpContext.Current.Server.MapPath("~/uploads/logo");
string targetPath = Path.Combine(targetFolder, yourFileName);
file.SaveAs(targetPath);
回答by SynerCoder
Your error is the following:
您的错误如下:
bool folder_exists3 = Directory.Exists(Server.MapPath("~/uploads/logo/" + fileName));
if(!folder_exists3)
Directory.CreateDirectory(Server.MapPath("~/uploads/logo/"+fileName));
You check if a directory exists, but you should check if the file exists:
您检查目录是否存在,但您应该检查文件是否存在:
File.Exists(....);
回答by AntSpiteri
Remove the last part of the path to save you have an extra "/"
删除路径的最后一部分以保存您有一个额外的“/”
It should be
它应该是
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName);
Also you do not have a file extension set.
您也没有设置文件扩展名。
回答by bansi
You need filename
你需要文件名
file.SaveAs(Server.MapPath("~/uploads/logo/" + fileName+"/" + your_image_fillename));