ios - 我从系统相册中上传图片到服务器,但是我的NSData是十六进制的,服务器要接受二进制的。 求问大神我怎么转?
阿神
阿神 2017-04-17 17:38:47
0
2
306
func sessionUpload(){
    //上传地址
    let url = NSURL(string: "http://www.zhekd.com/admin.php/Process/test")
    //请求
    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "POST"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData
    let session = NSURLSession.sharedSession()
    
    //上传数据流
    let adImage = qrCodeImage.image
    let adImageData = UIImageJPEGRepresentation(adImage!, 0.7)
    let data64String = adImageData?.base64EncodedStringWithOptions(NSDataBase64EncodingOptions())
    let dataImage2 = data64String!.dataUsingEncoding(NSUTF8StringEncoding)
    print(dataImage2)
    
    let uploadTask = session.uploadTaskWithRequest(request, fromData: dataImage2) {
        (data:NSData?, response:NSURLResponse?, error:NSError?) -> Void in
        if error != nil{
            print("发生了错误===========")
            print(error?.code)
            print(error?.description)
        }else{
            let str = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("上传完毕============")
            print(str)
        }
    }
    
    //使用resume方法启动任务
    uploadTask.resume()
}



我上传的代码是这个样子的。这个dataImage2是十六进制的,我要怎么样才能转成二进制的给服务器。                                                       

我曾经用先转成十进制,再转成二进制的方法,但是再转成十进制的时候,就报错了,方法如下,错误原因也没有提示,就是直接奔溃了,lldb  那种。


//十六进制 => 十进制
func hex2dec(num:String) -> Int64 {
    let str = num.uppercaseString
    var sum:Int64 = 0
    for i in str.utf8 {
        let s = sum*16
        let int = Int64(i)
        sum = s+int-48
        if i >= 65 {                 // A-Z 从65开始,但有初始值10,所以应该是减去55
            sum -= 7
        }
    }
    
    return sum
}

//十进制转二进制
func dec2bin(var number:Int64) -> String {
    var str = ""
    while number > 0 {
        str = "\(number % 2)" + str
        number /= 2
    }
    print(str)
    return str
}


阿神
阿神

闭关修行中......

reply all(2)
洪涛

I was surprised to see this hexadecimal to binary conversion algorithm. Do you want to use Int64 to save the value of an image? How could it be saved? ?

Regardless of why there is a need to convert to hexadecimal, this is something you need to discuss with your backend... If you really want to convert, you can save it by converting bit by bit... in hexadecimal One digit corresponds to 4 digits in the binary system. You should have learned it in college... 0 corresponds to 0000, F corresponds to 1111...

刘奇

Do you manage the server yourself? You can try converting it to base64 and sending it to the server for processing... As far as I know, it seems that iOS can send binaries... But we need to coordinate between the two parties

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template