簡體   English   中英

Swift 如何將圖像上傳到 model 內部的服務器

[英]Swift how to upload image to server inside model

我想將帶有一些信息的圖像發送到服務器。 服務器端正在接受 model 內部的請求,所以對我來說有兩個挑戰。

  1. 如何將圖像表示為我的模態 class
  2. 當服務器端使用 HttpFileBase 時,應該使用什么文件類型來精確匹配服務器端

所以下面是我在 swift 中的 model

public class ReceiptServiceModel: Codable {


  var   Id : String = ""
  var   UserId : Int64 = 0
  var   Name : String? = ""
  var   Notes : String? = ""
  var ReceiptFile : Data? = nil //<== this is the image representation type i can think for image file.

  }

以下是服務器端的 model (.Net)

public class ReceiptServiceModel
{
    public Guid Id { get; set; }
    public long UserId { get; set; }
    public string Name { get; set; }
    public HttpFileBase ReceiptFile { get; set; } //<== This one is confusing me....


}

那么應該使用什么將文件/圖像包裝到 Model class 以及我應該使用什么來匹配服務器端的確切類型。 檢查代碼片段中的注釋以清楚地查看造成混淆的字段。 提前致謝。

根據您的問題,我了解到您正在嘗試使用 POST 請求將圖像發送到服務器。 要使用 post 將圖像發送到服務器,您可以使用“Form-Data”,或者您需要將圖像轉換為 Base64 或 blob 格式,以便您可以將其添加到服務器可以接受的 JSON 文件中。

使用下面的 url 了解如何將圖像轉換為 blob: https://docs.couchbase.com/couchbase-lite/current/swift/blob.ZFC35FDC70D5FC69D269883A822C7A53

從以下鏈接安裝吊艙: https://docs.couchbase.com/couchbase-lite/current/swift/gs-install.html

可以試試下面的示例代碼:

 import CouchbaseLite-Swift

 public class ReceiptServiceModel: Codable {
  var   Id : String = ""
  var   UserId : Int64 = 0
  var   Name : String? = ""
  var   Notes : String? = ""
  var ReceiptFile : Blob? = nil
}

func convertImageToBlob() {
  guard let appleImage = UIImage(systemName: "edit") else {
     return
  }

  let imageData = appleImage.jpegData(compressionQuality: 1)!

  let blob = Blob(contentType: "image/jpeg", data: imageData)

  let model = ReceiptServiceModel()
  model.ReceiptFile = blob
 }

暫無
暫無

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

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