在上传到服务器asp.net核心之前更改文件名

时间:2017-04-08 07:36:23

标签: c# asp.net-mvc file-upload asp.net-core-mvc

  

嗨,我想在上传到服务器和存储路径之前更改文件名   在数据库中。这是我的代码。但它上传了同名文件。一世   想要改变名称(使用guid)。我怎么能这样做?

 [HttpPost, ValidateAntiForgeryToken]
        public async Task<IActionResult> SaveAsync(NewPostViewModel model, IFormFile postImage)
        {

            var unitOfWork = new UnitOfWork(new NewsDbContext(_contextOptions));

           // My domain class which is contains CoverPhotoPath property
            var post = new Post();

            if (postImage != null && postImage.Length > 0)
            {
                string filename = ContentDispositionHeaderValue.Parse(postImage.ContentDisposition).FileName.Trim('"');

                filename = this.EnsureCorrectFilename(filename);
                using (FileStream output = System.IO.File.Create(this.GetPathAndFilename(filename)))
                    await postImage.CopyToAsync(output);
             // this is my photo path in database 
                post.CoverPhotoPath = filename;
            }


            unitOfWork.Posts.Add(post);
            unitOfWork.Compelete();

            return RedirectToAction("List", "News");
        }
  

我的方法

private string EnsureCorrectFilename(string filename)
        {
            if (filename.Contains("\\"))
                filename = filename.Substring(filename.LastIndexOf("\\") + 1);

            return filename;
        }


 private string GetPathAndFilename(string filename)
    {
        return _environment.WebRootPath + "\\files\\" + filename;
    }

2 个答案:

答案 0 :(得分:2)

这是我使用FileStream的上传方法,希望有帮助

[HttpPost]
    public async Task<IActionResult> UploadFileImage(ICollection<IFormFile> files)
    {
        string file_name = "the file name";
        var uploads = Path.Combine(_environment.WebRootPath, "uploads/Image");
        foreach (var file in files)
        {
            if (file.Length > 0)
            {
                using (var fileStream = new FileStream(Path.Combine(uploads, file_name ), FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }
            }
        }
        return View();
    }

答案 1 :(得分:0)

我知道已经很晚了,但这也许可以帮上忙。 只需将旧文件复制到新文件,然后在上传文件后删除旧文件即可。像:

 var oldFilePath = folderPath + fileName; //filename: Uploading file
 using (FileStream fileStream = System.IO.File.Create(oldFilePath))
                {
                    await item.CopyToAsync(fileStream);

                }
 var newFileName = someCustomString + fileName;
 var newFilePath = folderPath + newFileName;

 System.IO.File.Copy(oldFilePath, newFilePath, true);
 System.IO.File.Delete(oldFilePath);