File Upload ASP.NET MVC 3.0

后端 未结 21 1239
无人共我
无人共我 2020-11-22 01:09

(Preface: this question is about ASP.NET MVC 3.0 which was released in 2011, it is not about ASP.NET Core 3.0 which was released in 2019)

I want to

21条回答
  •  春和景丽
    2020-11-22 01:43

    Checkout my solution

    public string SaveFile(HttpPostedFileBase uploadfile, string saveInDirectory="/", List acceptedExtention =null)
    {
        acceptedExtention = acceptedExtention ?? new List() {".png", ".Jpeg"};//optional arguments
    
        var extension = Path.GetExtension(uploadfile.FileName).ToLower();
    
        if (!acceptedExtention.Contains(extension))
        {
            throw new UserFriendlyException("Unsupported File type");
        }
        var tempPath = GenerateDocumentPath(uploadfile.FileName, saveInDirectory);
        FileHelper.DeleteIfExists(tempPath);
        uploadfile.SaveAs(tempPath);
    
        var fileName = Path.GetFileName(tempPath);
        return fileName;
    }
    
    private string GenerateDocumentPath(string fileName, string saveInDirectory)
    {
        System.IO.Directory.CreateDirectory(Server.MapPath($"~/{saveInDirectory}"));
        return Path.Combine(Server.MapPath($"~/{saveInDirectory}"), Path.GetFileNameWithoutExtension(fileName) +"_"+ DateTime.Now.Ticks + Path.GetExtension(fileName));
    }
    

    add these functions in your base controller so you can use them in all controllers

    checkout how to use it

    SaveFile(view.PassportPicture,acceptedExtention:new List() { ".png", ".Jpeg"},saveInDirectory: "content/img/PassportPicture");
    

    and here is a full example

    [HttpPost]
    public async Task CreateUserThenGenerateToken(CreateUserViewModel view)
    {// CreateUserViewModel contain two properties of type HttpPostedFileBase  
        string passportPicture = null, profilePicture = null;
        if (view.PassportPicture != null)
        {
            passportPicture = SaveFile(view.PassportPicture,acceptedExtention:new List() { ".png", ".Jpeg"},saveInDirectory: "content/img/PassportPicture");
        }
        if (view.ProfilePicture != null)
        {
            profilePicture = SaveFile(yourHttpPostedFileBase, acceptedExtention: new List() { ".png", ".Jpeg" }, saveInDirectory: "content/img/ProfilePicture");
        }
        var input = view.MapTo();
        input.PassportPicture = passportPicture;
        input.ProfilePicture = profilePicture;
    
    
        var getUserOutput = await _userAppService.CreateUserThenGenerateToken(input);
        return new AbpJsonResult(getUserOutput);
        //return Json(new AjaxResponse() { Result = getUserOutput, Success = true });
    
    }
    

提交回复
热议问题