【问题标题】:Why is the map.server virtual path not being saved to the database为什么 map.server 虚拟路径没有保存到数据库中
【发布时间】:2015-02-18 21:51:24
【问题描述】:

我一直坚持将文件上传的虚拟路径保存到我的数据库。没有虚拟路径,文件被保存,数据库中的 url 是文件的物理路径。所以当我尝试下载它时,我得到了不允许的本地资源。网址以 file:///C:path....
开头 当我使用断点时,我看到物理路径正在更改为虚拟路径,但是它例外。

api控制器

//POST
    public async Task<HttpResponseMessage> Post()
    {

        try
        {
            //saving the posted file to the harddisk
            string root = HttpContext.Current.Server.MapPath("~/Files/");
            var provider = new MultipartFormDataStreamProvider(root);
            await Request.Content.ReadAsMultipartAsync(provider);

            //Get Logged in User Name
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var user = manager.FindById(User.Identity.GetUserId());

            //getting the user details and storing in the object
            Document model = new Document();
            model.TypeId = Convert.ToInt32(provider.FormData["TypeId"]);
            model.TypeName = provider.FormData["TypeName"];
            model.PipeName = provider.FormData["PipeName"];
            model.DocumentUrl = provider.FormData["DocumentUrl"];
            model.DocumentUrl = model.DocumentUrl == "" ? null : model.DocumentUrl;

            //if there is a file then save that file to the desired location
            if (provider.FileData.Count > 0)
            {
                MultipartFileData fileData = provider.FileData[0];
                FileInfo fi = new FileInfo(fileData.LocalFileName);
                if (!Directory.Exists(fi.DirectoryName))
                {
                    Directory.CreateDirectory(fi.DirectoryName);
                }
                else
                {
                    //getting the file saving path
                    string clientFileName = fileData.Headers.ContentDisposition.FileName.Replace(@"""", "");
                    if (clientFileName != "")
                    {
                        string clientExtension = clientFileName.Substring(clientFileName.LastIndexOf('.'));
                        string space = ("-");
                        var dt = model.DocumentDate.ToString("y").Replace('/', '-').Replace(':', '-');
                        var CompanyName = model.CompanyName.Replace('_', ' ');

                        string vPath = root.Replace(@"C:\Development\TransparentEnergy\TransparentEnergy", "~").Replace("\\", "/");
                        string serverFileName = vPath + CompanyName + space + model.TypeName + space + model.CounterPartyName + space + dt + clientExtension;
                        model.DocumentUrl = serverFileName;



                        FileInfo fiOld = new FileInfo(vPath);
                        if (fiOld.Exists)
                            fiOld.Delete();
                        //if (File.Exists())
                        fi.MoveTo(serverFileName);
                    }
                    else
                    {
                        if (fi.Exists)
                            fi.Delete();
                    }
                }
            }
            //calling DB to save the user details
            using (var context = new ApplicationDbContext())
            {
                //save to db
                context.Documents.Add(model);
                context.SaveChanges();
            }
        }
        catch (Exception fex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, fex);
        }
        //sending the confirmation or error back to the user
        return Request.CreateResponse(HttpStatusCode.OK);
    }

断点:

model.DocumentUrl = serverFileName;

表演

“~/Files/Black Elk-Invoices-None-May 2006.pdf”

异常发生在这里

 FileInfo fiOld = new FileInfo(vPath);
  if (fiOld.Exists)
  fiOld.Delete();
//if (File.Exists())
  fi.MoveTo(serverFileName);

FiloInfo(vPath) 显示

~/文件/

异常发生在:

fi.MoveTo(serverFileName);

异常信息:

在 System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath) 在 System.IO.__Error.WinIOError() 在 System.IO.FileInfo.MoveTo(字符串 destFileName) 在 c:\Development\TransparentEnergy\TransparentEnergy\ControllersAPI\SubmitApi\apiInvoiceController.cs:line 87 中的 TransparentEnergy.ControllersAPI.apiInvoiceController.d__0.MoveNext() 处

更新

 //POST
    public async Task<HttpResponseMessage> Post()
    {

        try
        {
            //saving the posted file to the harddisk
            string root = HttpContext.Current.Server.MapPath("~/Files/");
            var provider = new MultipartFormDataStreamProvider(root);
            await Request.Content.ReadAsMultipartAsync(provider);

            //Get Logged in User Name
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var user = manager.FindById(User.Identity.GetUserId());

            //getting the user details and storing in the object
            Document model = new Document();
            model.TypeId = Convert.ToInt32(provider.FormData["TypeId"]);
            model.TypeName = provider.FormData["TypeName"];
            model.LocationId = Convert.ToInt32(provider.FormData["LocationId"]);
            model.LocationName = provider.FormData["LocationName"];
            model.PipeId = Convert.ToInt32(provider.FormData["PipeId"]);
            model.PipeName = provider.FormData["PipeName"];
            model.CompanyId = Convert.ToInt32(provider.FormData["CompanyId"]);
            model.CompanyName = provider.FormData["CompanyName"];
            model.PlantId = Convert.ToInt32(provider.FormData["PlantId"]);
            model.PlantName = provider.FormData["PlantName"];
            model.CounterPartyId = Convert.ToInt32(provider.FormData["CounterPartyId"]);
            model.CounterPartyName = provider.FormData["CounterPartyName"];
            string docDate = provider.FormData["DocumentDate"];
            model.DocumentDate = DateTime.Parse(docDate.Trim('"'));
            model.UploadedBy = user.Name;
            model.UploadDate = DateTime.Now;
            model.DocumentUrl = provider.FormData["DocumentUrl"];

            //if there is a file then save that file to the desired location
            if (provider.FileData.Count > 0)
            {
                MultipartFileData fileData = provider.FileData[0];
                FileInfo fi = new FileInfo(fileData.LocalFileName);

                //getting the file saving path
                string clientFileName = fileData.Headers.ContentDisposition.FileName.Replace(@"""", "");
                if (clientFileName != "")
                {
                    string clientExtension = clientFileName.Substring(clientFileName.LastIndexOf('.'));
                    string dash = ("-");
                    var dt = model.DocumentDate.ToString("y").Replace('/', '-').Replace(':', '-');
                    var CompanyName = model.CompanyName.Replace('_', ' ');

                    string vPath = root.Replace(@"C:\Development\TransparentEnergy\TransparentEnergy", "~").Replace("\\", "/");
                    string path = String.Format(CompanyName + dash + model.TypeName + dash + model.CounterPartyName + dash + dt + clientExtension);

                    string combination = Path.Combine(vPath, path);
                    model.DocumentUrl = combination;
                    FileInfo fiOld = new FileInfo(path);
                    if (fiOld.Exists)
                        fiOld.Delete();
                    //if (File.Exists())
                    fi.MoveTo(vPath);
                }
                else
                {
                    if (fi.Exists)
                        fi.Delete();
                }

            }
            //calling DB to save the user details
            using (var context = new ApplicationDbContext())
            {
                //save to db
                context.Documents.Add(model);
                context.SaveChanges();
            }
        }
        catch (Exception fex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, fex);
        }
        //sending the confirmation or error back to the user
        return Request.CreateResponse(HttpStatusCode.OK);
    }

这行得通!

 public async Task<HttpResponseMessage> Post()
    {

        try
        {
            //saving the posted file to the harddisk
            //string root = HttpContext.Current.Server.MapPath("~/Files/");
            string root = HostingEnvironment.MapPath(ConfigurationManager.AppSettings["~/Files/"]);
            var provider = new MultipartFormDataStreamProvider(root);
            await Request.Content.ReadAsMultipartAsync(provider);

            //Get Logged in User Name
            var manager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(new ApplicationDbContext()));
            var user = manager.FindById(User.Identity.GetUserId());

            //getting the user details and storing in the object
            Document model = new Document();
            model.TypeId = Convert.ToInt32(provider.FormData["TypeId"]);
            model.TypeName = provider.FormData["TypeName"];
            model.LocationId = Convert.ToInt32(provider.FormData["LocationId"]);
            model.LocationName = provider.FormData["LocationName"];
            model.PipeId = Convert.ToInt32(provider.FormData["PipeId"]);
            model.PipeName = provider.FormData["PipeName"];
            model.CompanyId = Convert.ToInt32(provider.FormData["CompanyId"]);
            model.CompanyName = provider.FormData["CompanyName"];
            model.PlantId = Convert.ToInt32(provider.FormData["PlantId"]);
            model.PlantName = provider.FormData["PlantName"];
            model.CounterPartyId = Convert.ToInt32(provider.FormData["CounterPartyId"]);
            model.CounterPartyName = provider.FormData["CounterPartyName"];
            string docDate = provider.FormData["DocumentDate"];
            model.DocumentDate = DateTime.Parse(docDate.Trim('"'));
            model.UploadedBy = user.Name;
            model.UploadDate = DateTime.Now;
            model.DocumentUrl = provider.FormData["DocumentUrl"];

            //if there is a file then save that file to the desired location
            if (provider.FileData.Count > 0)
            {
                MultipartFileData fileData = provider.FileData[0];
                FileInfo fi = new FileInfo(fileData.LocalFileName);

                //getting the file saving path
                string clientFileName = fileData.Headers.ContentDisposition.FileName.Replace(@"""", "");
                if (clientFileName != "")
                {
                    string clientExtension = clientFileName.Substring(clientFileName.LastIndexOf('.'));

                    var dt = model.DocumentDate.ToString("y").Replace('/', '-').Replace(':', '-');
                    var CompanyName = model.CompanyName.Replace('_', ' ');

                    string vPath = root.Replace(@"C:\Development\TransparentEnergy\TransparentEnergy", "~").Replace("\\", "/");
                    string fileName = String.Format("{0}-{1}-{2}-{3}{4}", CompanyName, model.TypeName, model.CounterPartyName, dt, clientExtension);
                    string combination = Path.Combine(vPath, fileName);
                    model.DocumentUrl = combination;

                    string physicalPath = HttpContext.Current.Server.MapPath("/Files");
                    string relativePath = Path.Combine(physicalPath, fileName);
                    FileInfo fiOld = new FileInfo(relativePath);
                    if (fiOld.Exists)
                        fiOld.Delete();
                    //if (File.Exists())
                    fi.MoveTo(relativePath);
                }
                else
                {
                    if (fi.Exists)
                        fi.Delete();
                }

            }
            //calling DB to save the user details
            using (var context = new ApplicationDbContext())
            {
                //save to db
                context.Documents.Add(model);
                context.SaveChanges();
            }
        }
        catch (Exception fex)
        {
            return Request.CreateErrorResponse(HttpStatusCode.NotFound, fex);
        }
        //sending the confirmation or error back to the user
        return Request.CreateResponse(HttpStatusCode.OK);
    }

【问题讨论】:

标签: c# asp.net-web-api2 fileinfo virtual-path


【解决方案1】:

我怀疑您的问题之所以发生是因为fi.MoveTo(serverFileName); 中的(错误命名的)serverFileName 实际上指向虚拟路径而不是物理路径。

请注意,我真的建议您重新考虑您的代码。一些例子:

  • string space = ("-");:“-”不是空格。
  • model.DocumentDate.ToString("y").Replace('/', '-').Replace(':', '-'); 似乎是一种糟糕的日期格式设置方式。
  • string serverFileName = vPath + CompanyName + space + model.TypeName + space + model.CounterPartyName + space + dt + clientExtension; 首先,使用Path.Combine 加入文件夹和文件名。其次,使用string.Format创建文件名而不是长连接不是更好吗?第三,serverFileName 恕我直言是个坏名字,我称之为路径。
  • 我真的不明白model.DocumentUrl 发生了什么:首先它获取provider.FormData["DocumentUrl"] 的值,然后检查model.DocumentUrl 是否为空字符串(请注意,最好使用string.Empty)如果是这种情况,请将其设置为 NULL,然后将其分配为 serverFileName

【讨论】:

  • 好的,我听从了你的建议。日期格式是否错误,或者是因为选择的格式?我更改了变量并使用了 Path.Combine 和 string.Format。我删除了第二个 model.DocumentUrl。结果相同。我更新了代码。我相信我有 FileInfo fiOld = new FileInfo(path);正确
  • 在您更新的代码中,FileInfo fiOld = new FileInfo(path); 现在指向文件名,而不是路径。但即使你使用combination,那仍然是一个virtual 路径(例如“~/Files/”)并且AFAIK FileInfo 需要一个physical 路径(例如“c:\文件\”)。 fi.MoveTo(vPath); 同上。另外,你的 string.Format 不正确,应该是string fileName = string.Format("{0}-{1}-{2}-{3}{4}", CompanyName, model.TypeName, model.CounterPartyName, dt, clientExtension);
  • 所以我会得到像这个字符串一样的物理路径 physicalPath = HttpContext.Current.Server.MapPath("/Files");然后在 FiloInfo(physicalPath) 中使用它
猜你喜欢
  • 1970-01-01
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-02-10
  • 1970-01-01
  • 1970-01-01
  • 2016-08-14
相关资源
最近更新 更多