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

时间:2016-12-27 10:03:00

标签: ios swift spring rest base64

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

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

更新:感谢Codo的建议:“您应该更具体地了解错误消息的位置。我的猜测就是在iOS中解析响应时。您的Swift代码需要JSON响应但是,在服务器端你只发送一个简单的字符串。这不合适。 - Codo“

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

此外,我添加了一些代码来检查图像数据是否采用'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;
  }
}

控制器:

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

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

1 个答案:

答案 0 :(得分:1)

行。我自己找到了解决方案。我希望它可以帮助像我这样的其他初学者。另外,感谢Codo的帮助。

首先,我得到的原因&#39;数据无法读取,因为它没有正确的格式&#39;我是FORGOT将&#39; Content-Type:application / json&#39; 添加到标题中。 iOS方面的代码应为:

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

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

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

为:

createImage(@RequestBody Image image)

我使用@RequestBody代替@RequestParamimage类包含两个文件:String fileString desc

这就是全部。它对我有用。