Cant write files do server with Filestream class (Return 400 - Bad Request)

我是研究僧i 提交于 2020-01-03 04:51:46

问题


When i try to write a image file to server, using this little code:

[HttpPost]
    public IActionResult Post([FromBody] ImgViewModel imagem)
    {

        try
        {
            if (imagem.base64.Contains(","))
            {
                imagem.base64 = imagem.base64
                  .Substring(imagem.base64
                  .IndexOf(",") + 1);
            }

            imagem.FileAsByteArray = Convert.FromBase64String(imagem.base64);

            var folderName = Path.Combine("Resources", "Images");
            var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);

            var ext = Path.GetExtension(imagem.filename);
            var fileName = Guid.NewGuid().ToString() + ext;
            var dbPath = Path.Combine(folderName, fileName);

            using (var fs = new FileStream(dbPath, FileMode.CreateNew))
            {
                fs.Write(imagem.FileAsByteArray, 0,
                         imagem.FileAsByteArray.Length);
                fs.Close();

            }

            ImageViewModel img = new ImageViewModel()
            {
                ExternalId = new Guid(imagem.id),
                Type = (ImageType)1,
                Url = dbPath

            };

            var imgx = Mapper.Map<ImageViewModel, Domain.Entities.Image>(img);

            _service.Add(imgx);
            _service.Commit();


            return new OkObjectResult(JsonConvert.SerializeObject(imagem));

        }
        catch (Exception)
        {

            throw;
        }

    }

I got a 400 - Bad Request error. I just commented this part of the code:

 using (var fs = new FileStream(dbPath, FileMode.CreateNew))
             {
                fs.Write(imagem.FileAsByteArray, 0,
                         imagem.FileAsByteArray.Length);
                fs.Close();

        }

and published it again, without Filestream file writing, and the rest of code worked fine. So, the error is in this part of the code.

Also, i've put this code on top of my class, trying to get server's permission to write these image files

[System.Security.Permissions.PermissionSet(System.Security.Permissions.SecurityAction.Demand, Name = "FullTrust")]

Also, in the server, i think that i've set correctly those permissions needed to write files

Anybody knows what i'm missing??

Thanks in advance.

来源:https://stackoverflow.com/questions/57515355/cant-write-files-do-server-with-filestream-class-return-400-bad-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!