簡體   English   中英

REST API - HTTP 文件上傳,狀態碼為 415

[英]REST API - HTTP Fileupload with Status Code 415

嗨,我正在構建一個 REST API 來上傳文件。

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.http.HttpEntity;



@Path("/api")
public class RestAPI {

    private final String UPLOADED_FILE_PATH = "C:/ProgramData/XXXX/";

    @GET
    public String getFile() {
     
        return "Loading File...";
    }

    @POST
    @Path("/image-upload")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    public Response uploadFile(HttpEntity input) throws IOException {
        // Do stuff
        return Response.status(200).entity("Uploaded file name : " + "").build();
    }

上傳者 Class:

import java.io.File;

import org.apache.http.HttpEntity;
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.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;

public class DemoFileUploader {
    public static void main(String args[]) throws Exception {
        DemoFileUploader fileUpload = new DemoFileUploader();
        File file = new File("C:/Users/tdr/Desktop/TestFile.txt");
        // Upload the file
        fileUpload.executeMultiPartRequest("http://localhost:8080/MediaHandler/mediahandler/api/image-upload",
                file, file.getName(), "File Uploaded :: TestFile.txt");
    }

    public void executeMultiPartRequest(String urlString, File file, String fileName, String fileDescription)
            throws Exception {

        // default client builder
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpPost postRequest = new HttpPost(urlString);
        try {
            FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);
            // Set various attributes
            HttpEntity multiPartEntity = MultipartEntityBuilder.create()
                    .addPart("fileDescription",
                            new StringBody(fileDescription != null ? fileDescription : "",
                                    ContentType.MULTIPART_FORM_DATA))
                    .addPart("fileName", new StringBody(fileName != null ? fileName : file.getName(),
                            ContentType.MULTIPART_FORM_DATA))
                    .addPart("attachment", fileBody).build();

            // Set to request body
            postRequest.setEntity(multiPartEntity);
            System.out.println("Sending Request....");
            System.out.println("Request: " + postRequest);
            System.out.println("Request Entity: " + postRequest.getEntity().getContentType());
            // Send request
            CloseableHttpResponse response = httpClient.execute(postRequest);
            System.out.println("Request executed.");

            // Verify response if any
            if (response != null) {
                System.out.println("Response Status Code: " + response.getStatusLine().getStatusCode());
                System.out.println("Response: " + response);
                System.out.println("Response Entity: " + response);
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

我得到以下 output:

發送請求....請求:POST http://localhost:8080/MediaHandler/mediahandler/api/image-upload HTTP/1.1 請求實體:Content-Type:multipart/form-data; 邊界=eINJSk3iptTJP7wf-cXlS-uznnnGMl99FyFmlet 請求已執行。 響應狀態代碼:415 響應:HTTP/1.1 415 [Content-Type: text/html;charset=utf-8, Content-Language: de, Content-Length: 785, Date: Wed, 31 Mar 2021 12:19:35 GMT,Keep-Alive:超時=20,連接:keep-alive] 響應實體:HTTP/1.1 415 [Content-Type:text/html;charset=utf-8,Content-Language:de,Content-Length:785,日期:格林威治標准時間 2021 年 3 月 31 日星期三 12:19:35,保持活動:超時 = 20,連接:保持活動]

我嘗試按照我找到的所有示例進行操作,但所有示例都與我的代碼相似。 你們能告訴我bug在哪里嗎?

我正在發送一個 multipart/form-data 並且我的 restapi 正在期待 multipart/form-data ...

您可以刪除此注釋:

@Consumes(MediaType.MULTIPART_FORM_DATA)

或請求 header 必須包含 Content-Type: MediaType.MULTIPART_FORM_DATA

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM