我正在學習asp.net mvc 3,現在我試圖實現一個應用程序,用戶可以將文件上傳到一個文件夾:使用asp.net mvc 3將文件上傳到文件夾時訪問被拒絕?
這是我的第一個實現,它實際上工作細,這裏是控制器代碼:
public class FileUploadController : Controller
{
//
// GET: /FileUpload/
public ActionResult Index()
{
return View();
}
[HttpPost]
[ActionName("Upload")]
public ActionResult Index(FormCollection form)
{
string upFolder = Server.MapPath("~/FileUploadFiles/");
if(!Directory.Exists(upFolder))
{
Directory.CreateDirectory(upFolder);
}
HttpPostedFileBase photo = Request.Files["fileupload"];
if (photo != null)
{
photo.SaveAs(upFolder+photo.FileName);
return RedirectToAction("Index");
}
return View();
}
}
這裏是我有另一種實現方式,我得到一個錯誤「訪問路徑‘UserUploads \上傳\’被拒絕。」這裏是處理上載的utitility類:
public static class FileUploader
{
public static char DirSeparator = Path.DirectorySeparatorChar;
public static string FilesPath = "UserUploads" + DirSeparator + "Uploads" + DirSeparator;
public static string UploadFile(HttpPostedFileBase file)
{
//check if we have a file
if(file == null)
{
return "";
}
//make sure the file has content
if(!(file.ContentLength > 0))
{
return "";
}
string fileName = file.FileName;
string fileExt = Path.GetExtension(file.FileName);
//make sure we are able to determine a proper extension
if(fileExt == null)
{
return "";
}
//check if directory does not exists
if(!Directory.Exists(FilesPath))
{
Directory.CreateDirectory(FilesPath);
}
//set our full path for saving
string path = FilesPath + DirSeparator + fileName;
//Save the file
file.SaveAs(Path.GetFullPath(path));
//Return the filename
return fileName;
}
public static void DeleteFile(string fileName)
{
//Don't do anything if there is no name
if(fileName.Length > 0)
{
return;
}
//Set our full path for deleting
string path = FilesPath + DirSeparator + fileName;
//Check if our file exists
if(File.Exists(Path.GetFullPath(path)))
{
File.Delete(Path.GetFullPath(path));
}
}
這裏是控制器代碼:
using MvcFileUpload.Utility;
namespace MvcFileUpload.Controllers
{
public class UploadFilesController : Controller
{
//
// GET: /UploadFiles/
public ActionResult Index()
{
return View();
}
[HttpPost]
[ActionName("Upload")]
public ActionResult Index(HttpPostedFileBase file)
{
FileUploader.UploadFile(file);
return RedirectToAction("Index");
}
}
}
這不是一個答案,但你應該看看靜態方法'System.IO.Path.Combine()'。它使得使用路徑更容易。它會爲您處理目錄分隔符,並且會很好地處理相對路徑。 – 2013-02-26 15:33:51
謝謝你的提示。 – 2013-02-26 15:37:14