ASP.. NET MVC文件上传工作在本地构建,不工作后部署
本文关键字:工作 构建 部署 MVC NET 文件 ASP | 更新日期: 2023-09-27 18:06:33
这段用于上传图像文件的代码在本地主机上构建时运行良好。但在部署时,它不工作,也没有给出任何错误。
我尝试将imagePath从/Content/Images/Items/
更改为~/Content/Images/Items/
和Content/Images/Items/
。仍无解
[HttpPost]
public ActionResult AddProduct(ProductDisplay productDisplay,HttpPostedFileBase upload)
{
bool isSaved = false;
string fileName = string.Empty;
string imagePath = string.Empty;
try
{
if(upload!=null && upload.ContentLength>0)
{
fileName = System.IO.Path.GetFileName(upload.FileName);
imagePath = "/Content/Images/Items/" + fileName;
upload.SaveAs(Server.MapPath(imagePath));
}
else
imagePath = "/Content/Images/Items/" + "NoImage.jpg";
productDisplay.ImagePath = imagePath;
ProductMangementBL balProduct = new ProductMangementBL();
isSaved = balProduct.AddProduct(productDisplay);
}
catch (Exception ex)
{
isSaved = false;
}
return RedirectToAction("ProductList", new RouteValueDictionary(new { controller = "Product", action = "ProductList", Id = productDisplay.CategoryID }));
}
检查事项:
var mapped = Server.MapPath(imagePath);
if (File.Exists(mapped))
{
//
}
else
{
throw new FileNotFoundException(imagePath);
}
也就是说,图片可能不存在
可能需要检查您的应用程序池是作为什么运行的,以及它是否具有写文件的权限。
您需要创建testProductAdd动作和相应的测试视图。
然后尝试只运行这段代码而不处理任何异常。
fileName = System.IO.Path.GetFileName(upload.FileName);
imagePath = "/Content/Images/Items/" + fileName;
upload.SaveAs(Server.MapPath(imagePath));
- 指定"Network Service"帐号到目标文件夹
- 然后给"网络服务"完全权限(不安全)。
- 然后将文件移动到另一个文件夹(可选选项)。
更安全的选项:
- 上传文件到另一个服务器
- 用防病毒软件 扫描文件
- 然后使用第三方软件(如MoveIt )将文件拉入生产服务器
- http://www.ipswitchft.com/moveit-managed-file-transfer
在你的异常处理中添加一个日志函数,因为现在你只是设置了一个布尔值,并且在退出函数之前再也不会使用它,因此丢失了异常中的信息。
将异常写入文本文件,它将为您提供错误的原因并指导您找到解决方案。
您可以使用像StreamWriter
一样简单的东西来将异常写入文本文件。
try
{
if(upload!=null && upload.ContentLength>0)
{
fileName = System.IO.Path.GetFileName(upload.FileName);
imagePath = "/Content/Images/Items/" + fileName;
upload.SaveAs(Server.MapPath(imagePath));
}
else
imagePath = "/Content/Images/Items/" + "NoImage.jpg";
productDisplay.ImagePath = imagePath;
ProductMangementBL balProduct = new ProductMangementBL();
isSaved = balProduct.AddProduct(productDisplay);
}
catch (Exception ex)
{
using (StreamWriter writer = new StreamWriter("C:''log.txt", true))
{
writer.WriteLine(ex);
}
}
这将把错误信息和堆栈跟踪写入C:驱动器中的文本文档"log.txt"。
可能是您的服务器上不存在相应的文件夹
保存文件前考虑检查文件夹是否存在:
string directory=Server.MapPath("/Content/Images/Items/");
if(!Directory.Exists(directory))
{
Directory.CreateDirectory(directory);
}
upload.SaveAs(Path.Combine(directory,fileName));