如何使用java将图片上传到wordpress媒体API

1tu0hz3e  于 2022-12-18  发布在  WordPress
关注(0)|答案(2)|浏览(181)

如何使用java将图片上传到wordpress API?Rest API的路径是wp-json/wp/v2/media

lyfkaqu1

lyfkaqu11#

答案二:
我修改了这段代码以使用java .NET.http --如果你需要制作一个模块化的应用程序,这会更好,因为apache commons还没有实现应用程序模块,所以你不能不费吹灰之力就打包。

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;
}

使用Vaadin获取uploadFile步骤文件的上传按钮的附加实现:

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;
    }
}
fykwrbwg

fykwrbwg2#

您可以上传图像文件(某些文件类型--默认情况下启用常用图像格式)(此处列出WP接受的完整上传格式列表:https://wordpress.com/support/accepted-filetypes/
我用来完成这一任务的代码如下:

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());

我的pomfile使用了这些,尽管版本不一定相同:

<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>

相关问题