【问题标题】:Upload image into asp.net web service in swift快速将图像上传到 asp.net 网络服务
【发布时间】:2015-04-23 20:37:13
【问题描述】:

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

我已经使用 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 Web 服务上的 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

【问题讨论】:

    标签: ios asp.net swift


    【解决方案1】:

    错误是将NSData 发送到 Asp.net 网络服务。

    1. 使用此代码将图像转换为 int base64

      let imageData = UIImageJPEGRepresentation(myImageView, 1)
      var base64String = imageData.base64EncodedStringWithOptions(.allZeros)
      
    2. 然后将其发送到 Web 服务并确保在您的 Web 服务中接收字符串数据,而不是 byte() 数组。

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

    就是这样!

    【讨论】:

      【解决方案2】:

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

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

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

      uploadFile="

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

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

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

      【讨论】:

      • 感谢您的评论对我很有帮助。
      猜你喜欢
      • 1970-01-01
      • 2019-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-22
      • 1970-01-01
      相关资源
      最近更新 更多