skip to Main Content

How do I upload an image to the wordpress API using java? The Rest API is path is wp-json/wp/v2/media

2

Answers


  1. Chosen as BEST ANSWER

    You can upload an image file (of certain file types -- common image formats are enabled by default (full WP accepted upload formats list here: https://wordpress.com/support/accepted-filetypes/ )

    The code I used to accomplish this is as follows:

    import org.apache.http.HttpEntity;
    import org.apache.http.HttpHeaders;
    import org.apache.http.client.methods.CloseableHttpResponse;
    import org.apache.http.client.methods.HttpPost;
    import org.apache.http.entity.ContentType;
    import org.apache.http.entity.mime.MultipartEntityBuilder;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
            CloseableHttpClient httpClient = HttpClients.createDefault();
            String encoded_cred = Base64.getEncoder().encodeToString(("username:pw").getBytes());
            String extension = "";
            String mime = "";
            String fileName = F.getName();
            int i = fileName.lastIndexOf('.');
            if (i > 0) {
                extension = fileName.substring(i + 1);
            }
            if (extension.equalsIgnoreCase("png")) {
                mime = "image/png";
            }
            if (extension.equalsIgnoreCase("jpeg")) {
                mime = "image/jpeg";
            }
        
            //endpoint and entity
            String uri = "https://www.<domain>.com/wp-json/wp/v2/media";
            HttpEntity entity = MultipartEntityBuilder.create()
                    .addBinaryBody("file", new FileInputStream(F), ContentType.create(mime), fileName)
                    .build();
    
    
            //request and execution
            HttpPost media = new HttpPost(uri);
            media.setEntity(entity);
            media.setHeader(HttpHeaders.AUTHORIZATION, "Basic " + encoded_cred);
            CloseableHttpResponse response = httpClient.execute(media);
            String resp = EntityUtils.toString(response.getEntity());
    

    My pomfile used these, though versions aren't necessarily the same:

    <dependencies>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.13</version>
        </dependency>
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpmime</artifactId>
            <version>4.5.13</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-text</artifactId>
            <version>1.9</version>
        </dependency>
    </dependencies>
    

  2. Answer 2:

    I revised this code to use java.net.http — this works better if you need to make a modular application since apache commons has yet to implement app modules so you can’t package without a big fuss.

    public static long uploadFile(File f, int counter, int size){
        String uri = "https://www.YOURDOMAIN.com/wp-json/wp/v2/media";
        String extension = "";
        String mime = "";
        String encoded_cred = Base64.getEncoder().encodeToString(("ACCOUNT:PASSWORD").getBytes());
        long mediaID = -1;
        String fileName = f.getName();
        int i = fileName.lastIndexOf('.');
        if (i > 0) {
            extension = fileName.substring(i + 1);
        }
        if (extension.equalsIgnoreCase("png")) {
            mime = "image/png";
        }
        if (extension.equalsIgnoreCase("jpeg") || extension.equalsIgnoreCase("jpg")) {
            mime = "image/jpeg";
        }
        Path fp = f.toPath();
        try {
            HttpClient client = HttpClient.newHttpClient();
            HttpRequest request = HttpRequest.newBuilder().uri(URI.create(uri))
                    .POST(HttpRequest.BodyPublishers.ofFile(fp) )
                    .headers("AUTHORIZATION", "Basic " + encoded_cred,
                             "Content-Disposition", "attachment; filename=" + f.getName(),
                             "Content-Type", mime
                            )
                    .build();
            HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
            System.out.println(response.body()); // output response body
    
    }catch (Exception e){e.printStackTrace(); AppendLog.appendLog("Upload failed for file: " + f.getName(), consoleLog);}
    
        return mediaID;
    }
    

    additional implementation of upload button using Vaadin to get file for the uploadFile step:

    import com.vaadin.flow.component.Component;
    import com.vaadin.flow.component.html.Div;
    import com.vaadin.flow.component.html.Image;
    import com.vaadin.flow.component.html.Label;
    import com.vaadin.flow.component.orderedlayout.FlexComponent;
    import com.vaadin.flow.component.orderedlayout.HorizontalLayout;
    import com.vaadin.flow.component.upload.Upload;
    import com.vaadin.flow.component.upload.receivers.MultiFileMemoryBuffer;
    import com.vaadin.flow.server.StreamResource;
    import org.apache.commons.io.FileUtils;
    
    import java.io.*;
    import java.util.ArrayList;
    import java.util.Random;
    
    public class SetImages {
        public static Component imageUpload(ArrayList<File> setImages, Div setHolder){
            Random random = new Random();
            var layout = new HorizontalLayout();
            var label = new Label("Select set images");
            MultiFileMemoryBuffer buffer = new MultiFileMemoryBuffer();
            Upload upload = new Upload(buffer);
            upload.addSucceededListener(event -> {
                String fileName = event.getFileName();
                InputStream fileData = buffer.getInputStream(fileName);
                int randFile = random.nextInt();
                File f = null;
                try {
                    f = File.createTempFile("setimg-" + randFile, ".jpg");
                }catch (IOException IE) {IE.printStackTrace();}
                Image img = new Image(new StreamResource(f.getName(), () ->{
                    try{
                        int rand = random.nextInt();
                        File imageFile = File.createTempFile("setimg-" + rand, ".jpg");
                        FileUtils.copyInputStreamToFile(fileData, imageFile);
                        setImages.add(imageFile);
                        return new FileInputStream(imageFile);
                    } catch (IOException fnf){fnf.printStackTrace();}
                    return null;
                }), "alt text");
                img.setWidth("250px");
                img.setHeight("400px");
                setHolder.add(img);
            });
            layout.setAlignItems(FlexComponent.Alignment.CENTER);
            layout.add(label, upload);
            return layout;
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search