上传文件,检查相同的文件名

时间:2014-01-12 16:28:39

标签: asp.net-mvc-4 linq-to-sql

您好我使用这个工具来进行文件上传和删除上传。 MVC 4 LINQ to SQL。

我想检查文件是否已上传,以及是否进行了播放 尝试新文件。

你可以帮助我,开始使用,为此添加代码吗?

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);
        }
    }
}

}

1 个答案:

答案 0 :(得分:0)

HttpPostedFileBase.FileName的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!
   ....