I need help to make fileupload.cs reusable for uploading gallery images in content/gallery folder and downloadable files in content/files folder. I believe the solution will be in making the filepaths string somehow dynamic. The gallery and File have different controllers,models and views. Below is the fileupload.cs code
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));
}
}
}
You can check if uploaded file has konwn image format extension (jpg, gif, png, etc) and if so then save to your content/gallery folder otherwise save to your content/files folder.
You are checking the file etension anyway
but you never use it.