samedi 26 octobre 2019

Can upload image using ASP.NET WEB API but not when deployed

I am using ASP.NET WEB API to upload image to server. But when i upload the source code of my web api to gearhost.com and make a post request. I am unable to post the image. This is my web api controller code:

        [Route("upload")]
    [HttpPost]

    public async Task<string> Upload()
    {


        var ctx = HttpContext.Current;
        var root = ctx.Server.MapPath("/uploads/");
        var provider =
            new MultipartFormDataStreamProvider(root);

        try
        {
            await Request.Content
                .ReadAsMultipartAsync(provider);

            foreach (var file in provider.FileData)
            {
                var name = file.Headers
                    .ContentDisposition
                    .FileName;

                // remove double quotes from string.
                name = name.Trim('"');

                var localFileName = file.LocalFileName;
                var filePath = Path.Combine(
                    root, "files", name);

                //File.Move(localFileName, filePath);

             //SaveFilePathSQLServerADO(localFileName, filePath);
                //SaveFileBinarySQLServerADO(localFileName, name);

                //SaveFilePathSQLServerEF(localFileName, filePath);
                    SaveFileBinarySQLServerEF(localFileName, name, filePath);

                if (File.Exists(localFileName))
                    File.Delete(localFileName);
            }
        }
        catch 
        {
            return "Error";
        }


        return "File uploaded successfuly!";
    }


    public void SaveFileBinarySQLServerEF(
     string localFile, string fileName, string filePath)
    {
        // 1) Get file binary
        byte[] fileBytes;
        using (var fs = new FileStream(
            localFile, FileMode.Open, FileAccess.Read))
        {
            fileBytes = new byte[fs.Length];
            fs.Read(
                fileBytes, 0, Convert.ToInt32(fs.Length));
        }

        // 2) Create a Files object
        var file = new tblimage()
        {
            Data = fileBytes,
            Names = fileName,
            ContentType = filePath


        };

        // 3) Add and save it in database
        using (var ctx = new coachEntities())
        {
            ctx.tblimages.Add(file);

            ctx.SaveChanges();
        }

    }

Here is the successful call from localhost: Image posted through localhost

However when deployed the same code and make request through postman then i get this error:

Image posted through live server




Aucun commentaire:

Enregistrer un commentaire