通过HTTPS POST发送图像?

时间:2017-03-09 01:40:34

标签: ios swift post https

我正在尝试将图像(使用UIImagePickerController从用户处获取)发送到寻找物理文件的API。 JPEG或PNG都可以...使用此代码...如何格式化它?

我的POST功能... postString中的“(图像变量)”应该是图像文件...

var request = URLRequest(url: URL(string: "web address.php")!)
            request.httpMethod = "POST"
            let postString = "action=setDefendentData&username=\("\(userNameString!)")&datetime=\(localDate)&latitude=\(latitude!)&longitude=\(longitude!)&image=\(image variable)"
            request.httpBody = postString.data(using: .utf8)
            let task = URLSession.shared.dataTask(with: request) { data, response, error in
                guard let data = data, error == nil else {

                    OperationQueue.main.addOperation{
                        loginAlertPopup(title: "Error", message: "Invalid Source: Check Internet Connection")
                    }

                    // check for fundamental networking error
                    print("error=\(error)")
                    return
                }

                if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {           // check for http errors
                    print("statusCode should be 200, but is \(httpStatus.statusCode)")
                    print("response = \(response)")

                }

                let responseString = String(data: data, encoding: .utf8)

                if responseString! == "success" {
                    print("Good")

                    // Success Alert \\
                    self.presentAlert(title: "Success", message: "Check-In has been updated!")
                }

                if responseString! == "fail" {

                    print("failed sending image")
                    print("Post String: \(postString)")
                    // Alert Error \\

                    OperationQueue.main.addOperation{
                        self.presentAlert(title: "Error", message: "Failed Sending Data")
                    }
                }
            }
            task.resume()
        }

这是我使用UIImagePickerController将图像保存到数据的代码:

 let fileDirectory : NSURL  = {
            return try! FileManager.default.url(for: .documentDirectory , in: .userDomainMask , appropriateFor: nil, create: true)
        }() as NSURL

        let imageQuality: CGFloat = 0.5
        let image = info[UIImagePickerControllerOriginalImage] as! UIImage

          // Saves to App Data
        let imagePath = fileDirectory.appendingPathComponent("uploadImage.jpg")
        guard let imageData = UIImageJPEGRepresentation(image, imageQuality) else {
            // handle failed conversion
            presentAlert(title: "Error", message: "Image Failure")
            print("jpg error")
            return
        }
        try! imageData.write(to: imagePath!)
            print("Image Path: \(imagePath!)")
            print("Image Size: \(imageData)")

        //Get Image
        let documentPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
        if let dirPath  = documentPath.first{
            let imageURL = URL(fileURLWithPath: dirPath).appendingPathComponent("uploadImage.jpg")
            let newImage    = UIImage(contentsOfFile: imageURL.path)

我尝试通过image变量(在这种情况下为newImage)发送,但它不接受它。我在我的视图控制器上创建了一个临时的UIImageView来显示newImage并相应地更新...... API处理程序只是不接受它。

有任何信息/帮助吗?

2 个答案:

答案 0 :(得分:0)

您无法通过将图像变量放在该帖子字符串中来上传图片

    let postString = "action=setDefendentData&username=\("\(userNameString!)")&datetime=\(localDate)&latitude=\(latitude!)&longitude=\(longitude!)&image=\(image variable)"
    request.httpBody = postString.data(using: .utf8)

相反,你的POST网址应该是这样的:

yourUrlDomain/action=setDefendentData&username=\("\(userNameString!)")&datetime=\(localDate)&latitude=\(latitude!)&longitude=\(longitude!)

您必须发布附加到httpBody的图像数据。

NSMutableData *body = [NSMutableData data];

// Add __VIEWSTATE
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Disposition: form-data; name=\"__VIEWSTATE\"\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"/wEPDwUKLTQwMjY2MDA0M2RkXtxyHItfb0ALigfUBOEHb/mYssynfUoTDJNZt/K8pDs=" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];

// add image data
NSData *imageData = UIImageJPEGRepresentation(image, 1.0);
if (imageData) {
    NSString *imageName = @"Any name you want";
    NSString *contentDisposition = [NSString stringWithFormat:@"Content-Disposition: form-data; name=\"imagefile\"; filename=\"%@\"\r\n",imageName];
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[contentDisposition dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}

[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

[request setHTTPBody:body];

不幸的是,我为Objective-C iOS应用程序制作了这段代码,而且我对Swift并不熟悉。但你明白了。

答案 1 :(得分:0)

public class FirstRunActivityLogger : IActivityLogger
{
    public async Task LogAsync(IActivity activity)
    {
        var allActivity = (Activity)activity;
        StateClient stateClient = allActivity.GetStateClient();
        BotData userData = await stateClient.BotState.GetUserDataAsync(activity.ChannelId, activity.From.Id);
        if (!userData.GetProperty<bool>("FirstRun"))
        {
            Debug.WriteLine($"From:{activity.From.Id} - To:{activity.Recipient.Id} - Message:{activity.AsMessageActivity()?.Text}");
            userData.SetProperty<bool>("FirstRun", true);
        }
    }
}

在参数dict

中设置参数,包括您需要上传的图像