首頁  >  文章  >  在 Postman 中使用圖像檔案傳送 JSON

在 Postman 中使用圖像檔案傳送 JSON

WBOY
WBOY轉載
2024-02-09 16:24:08790瀏覽

php小編西瓜將為您介紹如何在Postman中使用圖片檔案傳送JSON。 Postman是一款功能強大的API開發工具,可幫助開發人員進行介面測試和除錯。通常情況下,我們會使用Postman發送JSON數據,但是如果需要在JSON中包含圖像文件,該怎麼辦?本文將詳細介紹如何在Postman中透過一些簡單的步驟來實現這項功能,讓您更靈活地使用Postman進行介面測試。無論您是初學者還是有經驗的開發人員,都能從本文中獲得實用的技巧和知識。讓我們一起來了解吧!

問題內容

我想在 postman 中發送帶有圖像的 json 文件,但收到以下錯誤:

"status": 415,
"error": "unsupported media type",

專家控制器

package com.shayanr.homeservicespring.controller;

import com.shayanr.homeservicespring.entity.users.expert;
import com.shayanr.homeservicespring.service.expertservice;
import lombok.requiredargsconstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.multipartfile;

import java.io.file;
import java.io.ioexception;

@restcontroller
@requestmapping("/expert")
@requiredargsconstructor
public class expertcontroller {
    private expertservice expertservice;

    @postmapping("/register")
    public void register(@requestbody expert expert,
            @requestparam("image") multipartfile image) throws ioexception {
        expertservice.signup(expert, image);
    }
}

專家服務

@override
@transactional
public expert signup(expert expert, multipartfile image) throws ioexception {
    if (expert == null) {
        throw new nullpointerexception("null expert");
    }
    if (!validate.namevalidation(expert.getfirstname()) ||
            !validate.namevalidation(expert.getlastname()) ||
            !validate.emailvalidation(expert.getemail()) ||
            !validate.passwordvalidation(expert.getpassword())) {
        throw new persistenceexception("wrong validation");
    }
    string extension = filenameutils.getextension(image.getname());
    if (extension.equalsignorecase("video") || extension.equalsignorecase("mp4")) {
        throw new persistenceexception("invalid image format. only image files are allowed.");
    }
    expert.setconfirmation(confirmation.new);

    byte[] imageinbytes = image.getbytes();
    expert.setimage(imageinbytes);
    expertrepository.save(expert);
    return expert;

}

在郵差中,我的第一行是 json 和這個 json 檔

{
  "firstName": "Sasa",
  "lastName": "Weel",
  "email": "[email protected]",
  "password": "Sasasd1@",
  "signUpDate": "2024-01-31",
  "signUpTime": "10:00:00"
}

在第二行我設定了問題所在的圖片

解決方法

您的@requestparam("image") multipartfile image 參數看起來正確。

因此,您接下來應該做的就是確保告訴 spring 您希望允許多部分檔案。

這是一個範例 application.properties 設定:

spring.servlet.multipart.enabled=true

控制上傳大小的其他組態設定:

# Adjust these file size restrictions and location as nessessary
spring.servlet.multipart.max-file-size=2MB
spring.servlet.multipart.max-request-size=10MB
spring.servlet.multipart.location=/temp

我懷疑 @requestbody expert expert 參數應該與此有關。

以上是在 Postman 中使用圖像檔案傳送 JSON的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除