将图像上传到swift中的asp.net web服务

时间:2015-04-23 20:37:13

标签: ios asp.net swift

如何将图像上传到我的网络服务,然后我可以将其保存在我的服务器上!

我使用POST方法尝试了下面的代码,但是我收到了这个错误

(A potentially dangerous Request.Form value was detected from the client (uploadFile="<ffd8ffe0 00104a46 4...").)
func myImageUploadRequest() {
    let imageData = UIImageJPEGRepresentation(myImageView, 1)
    let boundary = generateBoundaryString()
    var base64String = imageData.base64EncodedStringWithOptions(.allZeros)

    let myUrl = NSURL(string: "http://xxxxx/UploadImageTest");
        let request = NSMutableURLRequest(URL:myUrl!);
        request.HTTPMethod = "POST";
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")


    if(imageData==nil) { return; }
    var body = NSMutableData();
    body.appendString("uploadFile=\(imageData)")
    request.HTTPBody = body
    let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
        data, response, error in

        if error != nil {
            println("error=\(error)")
            return
        }

        // You can print out response object
        println("******* response = \(response)")

        // Print out reponse body
        let responseString = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("****** response data = \(responseString!)")

        dispatch_async(dispatch_get_main_queue(),{
        });

    }

    task.resume()
}

这是我的Asp.net网络服务上的POST SOAP

    POST /xxxx.asmx/UploadImageTest HTTP/1.1
    Host: xxxx.com
Content-Type: application/x-www-form-urlencoded Content-Length: length

uploadFile=string&uploadFile=string

2 个答案:

答案 0 :(得分:2)

错误是将NSDate发送到Asp.net Web服务。 1-使用此代码将图像转换为base64

let imageData = UIImageJPEGRepresentation(myImageView, 1)
var base64String = imageData.base64EncodedStringWithOptions(.allZeros)

2-然后将其发送到Web服务并确保在您的Web服务中recive String数据而不是byte()数组。

3-在您的Web服务中将base64转换为Image并保存到您的服务器中。

就是这样!。

答案 1 :(得分:1)

我不熟悉Swift,但在Objective C中我会准备这样的数据:

....
NSMutableString* body = [NSMutableString new];
[body appendFormat:@"uploadFile=%@",base64String];
....

从错误描述中可以明显看出错误的原因。您可能会发现您的代码将base64图像字符串格式化为

  

uploadFile =&#34;&lt; ffd8ffe0 00104a46 4 ...

uploadFile=之后的文本根本不是base64编码的字符串,而是NSData的字符串表示,并且数据开头的额外<被视为html标记在服务器中。 ASP.NET请求验证不允许请求体中的此类标记作为安全措施,以防止代码/脚本注入和跨站点脚本。

即使您从服务器web.config或.asmx禁用请求验证,服务器仍然不会解释数据,因为它仍然不是服务器可能期望的有效base64格式。

所以我的建议是在将请求发送到服务器之前正确构建请求,一切都应该无缝地工作。