vcs
vcs

Reputation: 3725

A generic error occurred in GDI+ When uploading an image from Desktop application to web server using web api

I am trying to upload an image from my Windows Desktop application (VB.NET) to Web Server using web api

The Code runs correctly in local machine. but fails when run on web server with the error message A generic error occurred in GDI+.

The following is the WebApi Code which accepts the image

public void PostFile(ImageData objImage)

    {
        Image img = BytesToImage(objImage.ImageFile);
        string ImageName = objImage.EmployeeGUID.ToString() + ".Jpg";
        string FilePath = "";
        FilePath = System.Web.HttpContext.Current.Server.MapPath("~/photo") ;

        try { 
    img.Save(FilePath + '\\' + ImageName.ToString(), System.Drawing.Imaging.ImageFormat.Jpeg);
        }
        catch (Exception ex) {
        }
    }


  public class ImageData
  {
        public long EmployeeCode;
        public Guid EmployeeGUID; 
        public byte[] ImageFile ;
    }

    private Image BytesToImage(byte[] ImageBytes)
   {
        Image imgNew;
        MemoryStream memImage = new MemoryStream(ImageBytes);
        imgNew = Image.FromStream(memImage);
        return imgNew;
    }

The following code is VB.NET Code (Windows forms Application) from which image is
uploaded

Public Sub SendFile()

Dim EmployeeGUID As GUID
Dim EmployeeCode As long
    Dim ImagefileToSend As String
    Dim objImage As ImageData
    Dim client As New HttpClient


    client.BaseAddress = New Uri(WebApiPath)
    client.DefaultRequestHeaders.Accept.Add(New MediaTypeWithQualityHeaderValue("application/json"))

    objImage = New ImageData()
    objImage.EmployeeCode = EmployeeCode
    objImage.EmployeeGUID = EmployeeGUID
    objImage.ImageFile = ImageToBytes(Image.FromFile(ImagefileToSend))

    Dim jsonFormatter As MediaTypeFormatter = New JsonMediaTypeFormatter()
    Dim content As HttpContent = New ObjectContent(GetType(ImageData), objImage, jsonFormatter)
    Dim result As System.Net.Http.HttpResponseMessage

    Try
      result = client.PostAsync("api/GetFile", content).Result
    Catch ex As Exception
    End Try
End Sub

Private Class ImageData
    Public EmployeeCode As Long
    Public EmployeeGUID As Guid
    Public ImageFile As Byte()
End Class

Private Function ImageToBytes(ByVal image As Image) As Byte()
    Dim memImage As New IO.MemoryStream
    Dim bytImage() As Byte

    image.Save(memImage, image.RawFormat)
    bytImage = memImage.GetBuffer()

    Return bytImage
End Function

Upvotes: 1

Views: 1426

Answers (1)

vcs
vcs

Reputation: 3725

The Photo directory did not had write permission. Now it is working correctly

Upvotes: 2

Related Questions