如何在swift 2.2中将带有图像的json发布到外部服务器?

时间:2016-07-14 06:18:29

标签: ios json swift macos

我是ios的新手。我确实喜欢这样,但我得到了服务器的响应"需要MultipartFIle"参数'文件'不存在。

1)addUser方法我在我的按钮事件中调用。

func addUser(completion: (message: String?, error: String?) -> Void) -> NSURLSessionDataTask {
    // create the request method called here
    let request = createRequest()

    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
        if error != nil{
        print("@----->response",response)
        return// 400 Error is printed here
          }

    do {
        if let responseDictionary = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSDictionary {
            print("responseDictionary == \(responseDictionary)")


        }
    } catch {
        print(error)

        let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("responseString = \(responseString)")
    }
    }
    task.resume()

    return task
}

func createRequest() - > NSURLRequest {         让param = [

                "clientName" : self.projectClientNameField.text!,
                "clientAddress" : self.projectAddressField.text!,
                "clientNumber" : self.projectClientContactField.text!,
                "projectName" : self.projectNameField.text!,
                "projectDesc" : self.projectDetailsField.text!,
                "startDate"  : "",
                "endDate"  : "",
                ]



    let boundary = generateBoundaryString()

    let url = NSURL(string: "MYURL")!
    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"




    request.setValue("multipart/form-data; boundary=\(boundary)",  forHTTPHeaderField: "Content-Type")
    request.setValue("*/*", forHTTPHeaderField: "Accept")
    request.setValue("100-continue", forHTTPHeaderField: "Expect")

    //request.setValue("image/jpeg", forHTTPHeaderField: "Content-Type")
    let imageData = UIImagePNGRepresentation(image.image!)

    if imageData==nil{

        print("@-->imageData",imageData)
    }

    request.HTTPBody = createBodyWithParameters(param,  imageDataKey: imageData!, boundary: boundary)
    print("request -->",request)
    NSLog("%@", [request]);
    return request
}

func createBodyWithParameters(json: [String:AnyObject], imageDataKey: NSData, boundary: String) -> NSData {
    let body = NSMutableData()
    let key = "project"

    body.appendString("--\(boundary)\r\n")
   // body.appendString("Content-Type: application/json")
    body.appendString("Content-Disposition: form-data; name = \"\(key)\"\r\n\r\n")
    var requestBody = NSData()

    do {
        requestBody = try NSJSONSerialization.dataWithJSONObject(json, options: NSJSONWritingOptions(rawValue:0))
        print("@--->",requestBody)
    } catch (let e) {
        print(e)
    }
    body.appendData(requestBody)

    let mimetype = "image/png"

    let fileName = "suppliers.png"


      let name = "file"      
    //body.appendString("--\(boundary)\r\n")

    body.appendString("Content-Disposition: form-data; name=\"file\"; file=\"\(fileName)\"\r\n")
     body.appendString("Content-Type: \(mimetype)\r\n\r\n")
     body.appendData(imageDataKey)

    body.appendString("\r\n")
    print(body)

    body.appendString("--\(boundary)--\r\n")
    return body
}

func generateBoundaryString() -> String {
    return "------------------------\(NSUUID().UUIDString)"
}
服务器的

响应是:

{     错误="错误请求&#34 ;;     exception =" org.springframework.web.bind.MissingServletRequestParameterException&#34 ;;     message ="必需的MultipartFile参数' file'不存在&#34 ;;     path =" / project / create&#34 ;;     status = 400;     timestamp = 1468475579881; }

任何人都可以解决这个问题吗?

1 个答案:

答案 0 :(得分:0)

以下是上传图片的完整代码(您可以使用多张图片)在服务器上传。

您可以使用以下方法。 你必须传递paramDictionary和URL。

func createBodyWithParameters(parameters: NSMutableDictionary?,boundary: String) -> NSData {
    let body = NSMutableData()

    if parameters != nil {
        for (key, value) in parameters! {

            if(value is String || value is NSString){
                body.appendString("--\(boundary)\r\n")
                body.appendString("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n")
                body.appendString("\(value)\r\n")
            }
            else if(value is [UIImage]){
                var i = 0;
                for image in value as! [UIImage]{
                    let filename = "image\(i).jpg"
                    let data = UIImageJPEGRepresentation(image,1);
                    let mimetype = mimeTypeForPath(filename)

                    body.appendString("--\(boundary)\r\n")
                    body.appendString("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(filename)\"\r\n")
                    body.appendString("Content-Type: \(mimetype)\r\n\r\n")
                    body.appendData(data!)
                    body.appendString("\r\n")
                    i++;
                }


            }
        }
    }
    body.appendString("--\(boundary)--\r\n")
    //        NSLog("data %@",NSString(data: body, encoding: NSUTF8StringEncoding)!);
    return body
}

func generateBoundaryString() -> String {
    return "Boundary-\(NSUUID().UUIDString)"

}

func mimeTypeForPath(path: String) -> String {
    let pathExtension = path.pathExtension
    var stringMimeType = "application/octet-stream";
    if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension!, nil)?.takeRetainedValue() {
        if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() {
            stringMimeType = mimetype as NSString as String
        }
    }
    return stringMimeType;
}



func createRequest (param : NSMutableDictionary , strURL : String) -> NSURLRequest {

    let boundary = generateBoundaryString()

    let url = NSURL(string: strURL)
    let request = NSMutableURLRequest(URL: url!)

    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
    request.HTTPMethod = "POST"
    request.HTTPBody = createBodyWithParameters(param, boundary: boundary)

    return request
}