iOS 将 base64 编码图像上传到 RESTful 服务器时获取 http 400

标签 ios swift spring rest base64

我是服务器端编程的新手。目前,我正在为 iOS 应用程序开发 RESTful 服务器。

从我的 iOS 应用程序向 RESTful 服务器上传图像时,我收到 HTTP 响应 400 和错误消息“无法读取数据,因为它的格式不正确”。

更新:感谢 Codo 的建议:“您应该更具体地说明错误消息出现的位置。我猜是在您解析 iOS 中的响应时。您的 Swift 代码需要 JSON 响应. 然而,在服务器端你只是发送一个简单的字符串。那不适合。– Codo”

我在服务器端添加了一个仅包含 String 类型消息的 Result 类。 (这是一个简单的字符串响应,而不是类响应。)我在评论中添加了具体细节。

此外,我添加了一些代码来检查图像数据是否进入“createImage”方法。事实证明,数据永远不会进入“createImage”类。问题可能是由于传输图像数据的方式不正确造成的。

这是服务器端的代码:

结果类:

public class Result {
  private String message;

  public String getMessage() {
      return message;
  }

  public void setMessage(String message) {
      this.message = message;
  }

  public Result(String message) {
    super();
    this.message = message;
  }
}

Controller :

@PostMapping(value= "/images") 
public ResponseEntity<Result> createImage(@RequestParam("image") String file,@RequestParam("desc") String  desc){ 

  // check whether or not image data goes here
  try{
        PrintWriter writer = new PrintWriter("D:/cp/check.txt", "UTF-8");
        writer.println("image data is processing");
        writer.close();
  } catch (IOException e) {

  }
  //** file is never created **//

  //** so nothing happens below **/
  if (!file.isEmpty()) {
    try {
      byte[] imageByte= parseBase64Binary(file);

      String directory="D:/cp/" + desc + ".jpg";

      new FileOutputStream(directory).write(imageByte);

      Result result = new Result("You have successfully uploaded ");

      return new ResponseEntity<Result>(result, HttpStatus.OK);
    } catch (Exception e) {
      Result result = new Result("You failed to upload ");
      return new ResponseEntity<Result>(result, HttpStatus.OK);
    }
  } else {
    Result result = new Result("Unable to upload. File is empty.");
    return new ResponseEntity<Result>(result, HttpStatus.OK);
  }
}

这是 iOS 端的代码:

let serviceUrl = URL(string:"http://192.168.0.17:8080/rest/images/")

var request = URLRequest(url: serviceUrl!)

request.httpMethod = "POST"

let image = UIImage(named: "someImage")

let data = UIImagePNGRepresentation(image)

let base64: String! = data?.base64EncodedString()

let body = ["image": base64, "desc": "firstImage"]

do {    
  request.httpBody = try JSONSerialization.data(withJSONObject: body, options: .prettyPrinted)

  let session = URLSession.shared.dataTask(with: request) { 

    (data, response, err) in

    guard err == nil else {
      // Always no error
      print(error.localizedDescription)
      return
    }

    let httpResponse = response as! HTTPURLResponse

    print(httpResponse)
    // <NSHTTPURLResponse: 0x17003bfa0> { URL:  http://192.168.0.17:8080/rest/images/ } 
    // { status code: 400, headers {
    // Connection = close;
    // "Content-Language" = en;
    // "Content-Length" = 1099;
    // "Content-Type" = "text/html;charset=utf-8";
    // Date = "Tue, 27 Dec 2016 23:13:33 GMT";
    // } }

    do {
      let json = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! Dictionary<String, Any>
      // I pretty sure that parsing data as dictionary is correct because I used same code in many places and they work fine. 

      // code never reaches this line
      print(json.description)

    } catch {
      print(error.localizedDescription)
      // print: 'The data couldn't read because it isn't in the correct format'
      return
    }
  }

  session.resume()

} catch {
  print(error.localizedDescription)
  return
}

我已经做了很多研究,但仍然找不到解决方案。

最佳答案

好的。我自己找出解决办法。我希望它能帮助像我一样的其他初学者。另外,感谢 Codo 的帮助。

首先,我收到“数据无法读取,因为它的格式不正确”的原因是我忘记将 'Content-Type: application/json' 添加到 header 中. iOS端的代码应该是:

request.serValue("application/json", forHTTPHeaderField: "Content-Type")

其次,在服务器端,我改变

createImage(@RequestParam("image") String file,@RequestParam("desc") String desc)

到:

createImage(@RequestBody Image 图片)

我使用 @RequestBody 而不是 @RequestParamimage 类包含两个文件:String fileString desc

就是这样。它对我有用。

关于iOS 将 base64 编码图像上传到 RESTful 服务器时获取 http 400,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41343019/

相关文章:

ios - UIPageViewController Swift 中的当前页面索引

java - Spring JDBCtemplate ROWMapper 太慢

ios - UIViewController didRotateFromInterfaceOrientation : not being called

ios - 无法选择特定的标签索引显示在标签栏 Controller 中,始终显示第 0 个索引

ios - 使用 Swift 隐藏取消隐藏静态 TableView 单元格

ios - 更改 Segue 时选项卡栏消失

java - 在 Spring 和 Hibernate 中使用多个数据源

java - SpringBootTest - 如何在运行时配置中替换一个 bean?

ios - UIViewControllerAnimatedTransitioning 每隔一段时间才有效?

ios - UICollectionView 单元格之间的间距