MVC3 контролирует FilePath при загрузке файлов - PullRequest
0 голосов
/ 29 января 2012

Мне нужна помощь, чтобы файл fileupload.cs можно было повторно использовать для загрузки изображений галереи в папку content / gallery и загружаемых файлов в папку content / files. Я считаю, что решение будет в том, чтобы сделать строку filepaths как-то динамичной. Галерея и Файл имеют разные контроллеры, модели и виды. Ниже приведен код 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 голосов
/ 29 января 2012

Вы можете проверить, имеет ли загруженный файл собственное расширение формата изображения (jpg, gif, png и т. Д.), И если это так, то сохраните его в папку content / gallery, в противном случае сохраните в папку content / files.в любом случае проверяем, нет ли у вас файла

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

, но вы никогда не используете его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...