Asp.net mvc 4 上载文件,检查是否有相同的文件名
嗨,我正在使用这个utils,使文件上传和删除上传。MVC4LINQ到SQL 我想检查文件是否已经上传,如果,做一个消息 尝试新文件 你能帮助我,开始,为这个添加代码吗Asp.net mvc 4 上载文件,检查是否有相同的文件名,asp.net-mvc-4,linq-to-sql,Asp.net Mvc 4,Linq To Sql,嗨,我正在使用这个utils,使文件上传和删除上传。MVC4LINQ到SQL 我想检查文件是否已经上传,如果,做一个消息 尝试新文件 你能帮助我,开始,为这个添加代码吗 using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; namespace CFire2.SupplyConUtils { public static class FileUp
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
namespace CFire2.SupplyConUtils
{
public static class FileUpload
{
public static char DirSeparator =
System.IO.Path.DirectorySeparatorChar;
public static string FilesPath = "Content" +
DirSeparator + "SupplyUpload" + 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(FilesPath))
{
// If it doesn't exist, create the directory
Directory.CreateDirectory(FilesPath);
}
//// Set our full path for saving
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/SupplyUpload"), fileName);
// Save our file
file.SaveAs(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
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/SupplyUpload"), fileName);
// Check if our file exists
if (File.Exists(path))
{
// Delete our file
File.Delete(path);
}
}
}
}的MSDN文档
在派生类中重写时,获取
客户端上的文件
因此,您可能需要添加此行以正确执行检查
string fileName = Path.GetFileName(file.FileName);
然后
var path = Path.Combine(HttpContext.Current.Server.MapPath("~/Content/SupplyUpload"),
fileName);
if(File.Exists(path))
return "The file has been already uploaded!
....
嘿,史蒂夫工作得很好。