ios – 在Swift中使用multipart / form-data上传图像和参数

前端之家收集整理的这篇文章主要介绍了ios – 在Swift中使用multipart / form-data上传图像和参数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
[警告]
正如我所看到的那样,这个问题越来越受到关注,
我想告诉你不要使用以下任何代码.
当我问到这个问题时,斯威夫特还有不到一年的时间,行动速度很快,大多数图书馆都不是 Swift友好且不稳定的.
我强烈建议您尝试使用 Alamofire或其他库来完成这类任务.但不要自己动手.
[/警告]

我想将图像上传到Drupal端点.

我遇到的问题是我收到带有text / html内容类型的HTTP 200 OK响应.在HTML响应中,有一条明确的信息表明节点已正确创建.但是在服务器端,图像不与节点相关联.

另外,我不期望text / html,但是我在Accept标头中指定了application / json.

它已经可以在使用Android Rest Template的Android应用中运行.以下是供参考的代码

String url = getUrl("node/{info_id}/attach_file");

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.MULTIPART_FORM_DATA);

if (user.isLoggedIn()) {
    headers.add(user.getSessionName(),user.getSessionId());
    headers.add("X-CSRF-Token",user.getToken());
    headers.add("Cookie",user.getSessionName() + "=" + user.getSessionId());
}

MultiValueMap<String,Object> parts = new LinkedMultiValueMap<>();

parts.add("files[field_mobileinfo_image]",new FileSystemResource(info.getImageUri()));
parts.add("field_name","field_mobileinfo_image");

HttpEntity<MultiValueMap<String,Object>> request = new HttpEntity<>(parts,headers);
return getRestTemplate().exchange(url,HttpMethod.POST,request,Void.class,info.getId()).getBody();

我知道我没有在Android(Void.class)中检查响应,但一切正常,图像附加到服务器端的节点.

现在在Swift的iOS上我尝试了很多东西.

使用AFNetworking:

func upload(mobileInfo: MobileInfo) {
    let user = userService.load()
    let url = Config.buildUrl("")

    let manager = AFHTTPRequestOperationManager(baseURL: NSURL(string:url)!)
    let serializer = AFHTTPRequestSerializer()
    serializer.setValue(user.sessionId,forHTTPHeaderField: user.sessionName)
    serializer.setValue(user.token,forHTTPHeaderField: "X-CSRF-Token")
    serializer.setValue("\(user.sessionName)=\(user.sessionId)",forHTTPHeaderField: "Cookie")
    manager.requestSerializer = serializer

    manager.responseSerializer.acceptableContentTypes.removeAll(keepCapacity: false)
    manager.responseSerializer.acceptableContentTypes.insert("application/json")

    let imageData = UIImageJPEGRepresentation(mobileInfo.image,0.3)    
    manager.POST("/node/\(mobileInfo.id)/attach_file",parameters: nil,constructingBodyWithBlock: { (formData) -> Void in
        formData.appendPartWithFileData(
            imageData,name: "files[field_mobileinfo_image]",fileName: "field_mobileinfo_image",mimeType: "image/jpeg")
        formData.appendPartWithFormData("field_mobileinfo_image".dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion: true),name: "field_name")
    },success: { (operation,data) -> Void in
        println(data)
    }) { (operation,error) -> Void in
        println(error)
    }
}

手动从其他stackoverflow问题中获取信息:

func upload2(mobileInfo: MobileInfo) {
    let user = userService.load()
    let imageData = UIImageJPEGRepresentation(mobileInfo.image,0.3)
    let url = NSURL(string:Config.buildUrl("/node/\(mobileInfo.id)/attach_file"))!
    println(url)
    var request = NSMutableURLRequest(URL: url)
    var session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"
    var boundary = "---------------------------14737809831466499882746641449"
    var contentType = "multipart/form-data; boundary=\(boundary)"
    println(contentType)
    request.addValue(contentType,forHTTPHeaderField: "Content-Type")
    request.addValue("application/json",forHTTPHeaderField: "Accept")
    request.addValue("\(user.sessionName)=\(user.sessionId)",forHTTPHeaderField: "Cookie")
    request.addValue(user.sessionId,forHTTPHeaderField: user.sessionName)
    request.addValue(user.token,forHTTPHeaderField: "X-CSRF-Token")

    println(request.allHTTPHeaderFields)

    var body = NSMutableData()

    body.appendData("\r\n--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Disposition: form-data; name=\"field_name\"\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("field_mobileinfo_image".dataUsingEncoding(NSUTF8StringEncoding,allowLossyConversion: true)!)

    body.appendData("\r\n--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Disposition: form-data; name=\"files[field_mobileinfo_image]\"; filename=\"img.jpg\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData("Content-Type: application/octet-stream\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)
    body.appendData(imageData)
    body.appendData("\r\n--\(boundary)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!)


    var returnData = NSURLConnection.sendSynchronousRequest(request,returningResponse: nil,error: nil)

    var returnString = NSString(data: returnData!,encoding: NSUTF8StringEncoding)

    println("returnString \(returnString)")
}

使用SRWebClient:

func upload3(mobileInfo: MobileInfo) {
    let user = userService.load()
    let imageData:NSData = NSData(data: UIImageJPEGRepresentation(mobileInfo.image,0.3))
    SRWebClient.POST("http://master.test.lesfrontaliers.lu/node/\(mobileInfo.id)/attach_file")
        .headers(["Accept": "application/json",user.sessionName: user.sessionId,"X-CSRF-Token": user.token,"Cookie": "\(user.sessionName)=\(user.sessionId)"])
        .data(imageData,fieldName:"files[field_mobileinfo_image]",data:["field_name":"field_mobileinfo_image"])
        .send({ (response: AnyObject!,status: Int) -> Void in
            println(status)
            println(response)
        },failure:{(error:NSError!) -> Void in
            println(error)
        })
}

请救救我! 原文链接:https://www.f2er.com/iOS/334459.html

猜你在找的iOS相关文章