MVC3在fileupload中控制FilePath

时间:2012-01-28 22:03:35

标签: asp.net-mvc-3 file-upload

我需要帮助才能使fileupload.cs可以重复上传内容/图库文件夹中的图库图像和内容/文件文件夹中的可下载文件。我相信解决方案将使文件路径字符串以某种方式动态。图库和文件具有不同的控制器,模型和视图。下面是fileupload.cs代码

public static class FileUpload

{
    public static char DirSeparator =  System.IO.Path.DirectorySeparatorChar;
    public static string FilesPath = "Content" + DirSeparator + "Files" + DirSeparator;
    public static string UploadFile(HttpPostedFileBase file)
    {
        // Check if we have a file
        if (null == file) 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 were able to determine a proper 
        // extension
        if (null == fileExt) return "";
        // Check if the directory we are saving to exists
        if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory+FilesPath))
        {
        // If it doesn't exist, create the directory
            Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory+FilesPath);
        }
        // Set our full path for saving
        string path = FilesPath + DirSeparator + fileName;
        // Save our file
        //file.SaveAs(Path.GetFullPath(path));
        file.SaveAs(Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory +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(AppDomain.CurrentDomain.BaseDirectory+path)))
        {
            // Delete our file
            File.Delete(Path.GetFullPath(AppDomain.CurrentDomain.BaseDirectory+path));
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您可以检查上传的文件是否具有konwn图像格式扩展名(jpg,gif,png等),如果是,则保存到您的内容/图库文件夹,否则保存到您的内容/文件夹。

您正在检查文件扩展

string fileExt = Path.GetExtension(file.FileName);

但你从不使用它。