1

I have a problem uploading an image to Wordpress from a VB .NET project (using Restsharp). I create the client and the request for this, I added a header with the authorization, parameters...) but, when I execute the request, this response Status OK (200) but the image has not create in Wordpress.

I tried all this sentences, and no works:

Test 1:

Dim client As RestClient = New RestClient("http://domain-example.com/wp-json/wp/v2/media")
client.Timeout = -1
Dim request As RestRequest = New RestRequest(Method.POST)
request.AddHeader("Authorization", "Basic {base64code}")
request.AddHeader("Cookie", "PHPSESSID=b83jbtsfjbb2bkkso7s75m75il")
request.AddHeader("Content-Disposition", "attachment; filename=Google-logo.jpg")
request.AddHeader("Content-Type", "image/jpeg")
request.AddFile("file", "C:\temp\Google-logo.jpg")
request.AddParameter("title", "titleExample")
request.AddParameter("caption", "captionExample")
Dim response As IRestResponse = client.Execute(request)
Console.WriteLine(response.StatusCode)

Test 2:

Dim client As RestClient = New RestClient("http://domain-example.com/wp-json/wp/v2/media")
client.Timeout = -1
Dim request As RestRequest = New RestRequest(Method.POST)
request.AddHeader("Authorization", "Basic {base64code}")
request.AddHeader("Cookie", "PHPSESSID=b83jbtsfjbb2bkkso7s75m75il")
request.AddParameter("title", "titleExample")
request.AddParameter("caption", "captionExample")
request.AlwaysMultipartFormData = True
request.AddParameter("file", "C:\temp\Google-logo.png")
Dim response As IRestResponse = client.Execute(request)
Console.WriteLine(response.StatusCode)

Test 3:

Dim client as RestClient = New RestClient("http://domain-example.com/wp-json/wp/v2/media")
client.Timeout = -1
Dim request = New RestRequest(Method.POST)
request.RequestFormat = DataFormat.Json
request.AddHeader("Authorization", "Basic {base64code}")
request.AddFileBytes("file", BytesImage, "C:\temp\Google-logo.jpg", "image/jpeg")
request.AddParameter("title", "tempFile")
request.AddParameter("caption", "tempFileCaption")
Dim response As IRestResponse = client.Execute(request)
Console.WriteLine(response.Content)

Test 4: In this example I not use RestSharp, I used the HttpWebRequest, and the same result

Dim myReq As HttpWebRequest
Dim myResp As HttpWebResponse

myReq = HttpWebRequest.Create("http://domain-example.com/wp-json/wp/v2/media")

myReq.Method = "POST"
myReq.ContentType = "application/json"
myReq.Headers.Add("Authorization", "Basic " & Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes("user:password")))
Dim myData As String = "c:\temp\Google-logo.jpg"
myReq.GetRequestStream.Write(System.Text.Encoding.UTF8.GetBytes(myData), 0, System.Text.Encoding.UTF8.GetBytes(myData).Count)
myResp = myReq.GetResponse
Dim myreader As New System.IO.StreamReader(myResp.GetResponseStream)
Dim myText As String
myText = myreader.ReadToEnd

I tried to simulate the upload using Postman, but I can't.

I don't know why it's so hard to upload an image to Wordpress using REST...

Disclaimer: Also, this post doesn't work for me

4 Answers 4

1

The following is from the docs.

To add a file to the request you can use the RestRequest function called AddFile. The main function accepts the FileParameter argument:

request.AddFile(fileParameter);

You can instantiate the file parameter using FileParameter.Create that accepts a bytes array or FileParameter.FromFile, which will load the file from disk.

There are also extension functions that wrap the creation of FileParameter inside:

// Adds a file from disk
AddFile(parameterName, filePath, contentType);

// Adds an array of bytes
AddFile(parameterName, bytes, fileName, contentType);

// Adds a stream returned by the getFile function
AddFile(parameterName, getFile, fileName, contentType);

Remember that AddFile will set all the necessary headers, so please don't try to set content headers manually. Your code sets a lot of content headers, and it's unnecessary, and might be breaking your requests.

You can always use https://requestbin.com and send your requests there to inspect the content of those requests, so you can see if they match the expected request format.

Sign up to request clarification or add additional context in comments.

Comments

1

In test 1, remove or comment out this line of code:

request.AddHeader("Content-Type", "image/jpeg")

Comments

0

The solution for this is activate the JWT authentication plugin for Wordpress. By default, Wordpress avoid any POST call, the basic authentication doesn't work.

So, once activated the JWT (following the process), you must create a Token (using POST to the JWT endpoint) and put the Token in the POST process to create anything (posts, media, etc.)

Comments

0

It took me a long time to figure out how to upload a media file using .NET C#. Here's the solution that works well for me.

You will need an application password. This can be generated on the wp-admin site Users -> Profile -> Application Passwords (make sure you copy the generated password).

I use RestSharp version 112.1.0 available with NuGet packages.

public async System.Threading.Tasks.Task<string> WPfileUpload(string filePath, string fileLabel)
{

    return await System.Threading.Tasks.Task.Run(() =>
    {
        string path = filePath; // example @"C:\inetpub\websites\intranet\departments\sales\sample1.jpg";
                             

        string userName = "WPadmin User";
        string passWrd = "application password";  

        var client = new RestSharp.RestClient("https://yoursite.site/wp-json/wp/v2/media/");
        var request = new RestSharp.RestRequest(RestSharp.Method.POST);
        request.AddHeader("Authorization", " Basic " + Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(userName + ":" + passWrd)));
        request.AddHeader("Content-Disposition", "form-data; filename=\"" + path + "\"");

        request.AddFile("file", path);
        request.AddParameter("title", fileLabel);
        request.AddParameter("caption", fileLabel);

        request.Timeout = 240000;
        RestSharp.IRestResponse response = client.Execute(request);

        return response.Content;

    });

}

Then to call this function:

System.Threading.Tasks.Task.Run(async () =>
{
   await WPfileUpload(@"C:\inetpub\websites\intranet\departments\sales\sample1.jpg", 
   "title-caption"); 
              
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.