iOS开发中会经常用到文件上传下载的功能,这篇文件将介绍一下使用asp.net webservice实现文件上传下载。

首先,让我们看下文件下载。

这里我们下载cnblogs上的一个zip文件。使用NSURLRequest+NSURLConnection可以很方便的实现这个功能。

同步下载文件:

        NSString *urlAsString =@"http://files.cnblogs.com/zhuqil/UIWebViewDemo.zip";

NSURL *url = [NSURL URLWithString:urlAsString];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSError *error = nil;

NSData *data = [NSURLConnection sendSynchronousRequest:request

returningResponse:nil

error:&error];
/* 下载的数据 */
if (data != nil){

NSLog(@"下载成功");
if ([data writeToFile:@"UIWebViewDemo.zip" atomically:YES]) {

NSLog(@"保存成功.");

}
else

{

NSLog(@"保存失败.");

}

} else {

NSLog(@"%@", error);

}

异步下载文件:

- (void)viewDidLoad

{

[super viewDidLoad];
//文件地址
NSString *urlAsString =@"http://files.cnblogs.com/zhuqil/UIWebViewDemo.zip";

NSURL *url = [NSURL URLWithString:urlAsString];

NSURLRequest *request = [NSURLRequest requestWithURL:url];

NSMutableData *data = [[NSMutableData alloc] init];

self.connectionData = data;

[data release];

NSURLConnection *newConnection = [[NSURLConnection alloc]

initWithRequest:request
delegate:self

startImmediately:YES];

self.connection = newConnection;

[newConnection release];
if (self.connection != nil){

NSLog(@"Successfully created the connection");

} else {

NSLog(@"Could not create the connection");

}

}

- (void) connection:(NSURLConnection *)connection

didFailWithError:(NSError *)error{

NSLog(@"An error happened");

NSLog(@"%@", error);

}
- (void) connection:(NSURLConnection *)connection

didReceiveData:(NSData *)data{

NSLog(@"Received data");

[self.connectionData appendData:data];

}
- (void) connectionDidFinishLoading

:(NSURLConnection *)connection{
/* 下载的数据 */

NSLog(@"下载成功");
if ([self.connectionData writeToFile:@"UIWebViewDemo.zip" atomically:YES]) {

NSLog(@"保存成功.");

}
else

{

NSLog(@"保存失败.");

}

/* do something with the data here */

}
- (void) connection:(NSURLConnection *)connection

didReceiveResponse:(NSURLResponse *)response{

[self.connectionData setLength:0];

}

- (void) viewDidUnload{

[super viewDidUnload];

[self.connection cancel];

self.connection = nil;

self.connectionData = nil;

}

从上面两段代码中可以看到同步与异步下载的区别,大部分时候我们使用异步下载文件。在asp.net webservice中可以将文件的地址返回到iOS系统,iOS系统在去请求下载该文件。

上传文件

我们先使用VB.Net写一个webservice方法,用于接收上传上来的文件数据,代码如下。

    <WebMethod(Description:="上传文件!")> _
Public Function UploadFile() As XmlDocument
        Dim doc As XmlDocument = New XmlDocument()
        Try
            Dim postCollection As HttpFileCollection = Context.Request.Files
            Dim aFile As HttpPostedFile = postCollection("media")
            aFile.SaveAs(Server.MapPath(".") + "/" + Path.GetFileName(aFile.FileName))
            doc.LoadXml("<xml>ok</xml>")
            Return doc
        Catch ex As Exception
            doc.LoadXml("<xml>fail</xml>")
            Return doc
        End Try
    End Function

文件上传接口

定义一个类PicOperation用于处理上传图片:

@interface PicOperation : NSOperation
{
    UIImage *theImage;
}
@property (retain) UIImage *theImage;
@end
//
//  PicOperation.m
//  DownLoading
//
//  Created by skylin zhu on 11-7-30.
//  Copyright 2011年 mysoft. All rights reserved.
//
 
#import "PicOperation.h"
 
#define NOTIFY_AND_LEAVE(X) {[self cleanup:X]; return;}
#define DATA(X) [X dataUsingEncoding:NSUTF8StringEncoding]
 
// Posting constants
#define IMAGE_CONTENT @"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n"
#define STRING_CONTENT @"Content-Disposition: form-data; name=\"%@\"\r\n\r\n"
#define MULTIPART @"multipart/form-data; boundary=------------0x0x0x0x0x0x0x0x"
 
@implementation PicOperation
@synthesize theImage;
 
//创建postdata
- (NSData*)generateFormDataFromPostDictionary:(NSDictionary*)dict
{
    id boundary = @"------------0x0x0x0x0x0x0x0x";
    NSArray* keys = [dict allKeys];
    NSMutableData* result = [NSMutableData data];
     
    for (int i = 0; i < [keys count]; i++)
    {
        id value = [dict valueForKey: [keys objectAtIndex:i]];
        [result appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
         
        if ([value isKindOfClass:[NSData class]])
        {
            // handle image data
            NSString *formstring = [NSString stringWithFormat:IMAGE_CONTENT, [keys objectAtIndex:i]];
            [result appendData: DATA(formstring)];
            [result appendData:value];
        }
        else
        {
            // all non-image fields assumed to be strings
            NSString *formstring = [NSString stringWithFormat:STRING_CONTENT, [keys objectAtIndex:i]];
            [result appendData: DATA(formstring)];
            [result appendData:DATA(value)];
        }
         
        NSString *formstring = @"\r\n";
        [result appendData:DATA(formstring)];
    }
     
    NSString *formstring =[NSString stringWithFormat:@"--%@--\r\n", boundary];
    [result appendData:DATA(formstring)];
    return result;
}
//上传图片
- (NSString *) UpLoading
{
    if (!self.theImage)
        NOTIFY_AND_LEAVE(@"Please set image before uploading.");
     
     
    NSMutableDictionary* post_dict = [[NSMutableDictionary alloc] init];
     
    [post_dict setObject:@"Posted from iPhone" forKey:@"message"];
    [post_dict setObject:UIImageJPEGRepresentation(self.theImage, 0.75f) forKey:@"media"];
     
    NSData *postData = [self generateFormDataFromPostDictionary:post_dict];
    [post_dict release];
     
    NSString *baseurl = @"http://10.5.23.121:7878/WorkflowService.asmx/UploadFile";
    NSURL *url = [NSURL URLWithString:baseurl];
    NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
    if (!urlRequest) NOTIFY_AND_LEAVE(@"Error creating the URL Request");
     
    [urlRequest setHTTPMethod: @"POST"];
    [urlRequest setValue:MULTIPART forHTTPHeaderField: @"Content-Type"];
    [urlRequest setHTTPBody:postData];
     
    // Submit & retrieve results
    NSError *error;
    NSURLResponse *response;
    NSLog(@"Contacting TwitPic....");
    NSData* result = [NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error];
    if (!result)
    {
        [self cleanup:[NSString stringWithFormat:@"Submission error: %@", [error localizedDescription]]];
        return;
    }
     
    // Return results
    NSString *outstring = [[[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding] autorelease];
    return outstring;
}
@end

这里我主要定义了两个方法,一个是generateFormDataFromPostDictionary用于创建post form data,一个是UpLoading供调用的类上传图片,这个类需要一个UIimage的对象。

类定义好了,上传图片就非常方便了,看下面代码:

PicOperation *pic = [[PicOperation alloc] init];
pic.theImage=[UIImage imageNamed:@"meinv4.jpg"];;
NSString *result = [pic UpLoading];
NSLog(result);

总结:这篇文章讲述了如何在iOS中结合asp.net webservice实现文件的上传和下载功能。

本文转自麒麟博客园博客,原文链接:http://www.cnblogs.com/zhuqil/archive/2011/07/30/2122019.html,如需转载请自行联系原作者

iOS开发之结合asp.net webservice实现文件上传下载的更多相关文章

  1. iOS开发之网络编程--使用NSURLConnection实现文件上传

    前言:使用NSURLConnection实现文件上传有点繁琐.    本文并没有介绍使用第三方框架上传文件. 正文: 这里先提供用于编码测试的接口:http://120.25.226.186:3281 ...

  2. WebService实现文件上传下载

    一:服务端:一个普通java web工程 package com.wzh.file; import com.sun.xml.ws.developer.StreamingAttachment; impo ...

  3. WebService完成文件上传下载

    由于开发需要使用webservice,第一个接触的工具叫axis2.项目开发相关jar下载. service端: 启动类: import java.net.InetAddress; import ja ...

  4. ios开发网络学习五:输出流以及文件上传

    一:输出流 #import "ViewController.h" @interface ViewController ()<NSURLConnectionDataDelega ...

  5. [SAP ABAP开发技术总结]客户端文本文件、Excel文件上传下载

    声明:原创作品,转载时请注明文章来自SAP师太技术博客( 博/客/园www.cnblogs.com):www.cnblogs.com/jiangzhengjun,并以超链接形式标明文章原始出处,否则将 ...

  6. webservice文件上传下载

    使用DataHandler实现webservice的文件上传下载 服务端代码: package com.hello.weChat.controller; import javax.activation ...

  7. C#微信公众号开发系列教程六(被动回复与上传下载多媒体文件)

    微信公众号开发系列教程一(调试环境部署) 微信公众号开发系列教程一(调试环境部署续:vs远程调试) C#微信公众号开发系列教程二(新手接入指南) C#微信公众号开发系列教程三(消息体签名及加解密) C ...

  8. ASP.NET中的文件上传大小限制的问题

    一.文件大小限制的问题 首先我们来说一下如何解决ASP.NET中的文件上传大小限制的问题,我们知道在默认情况下ASP.NET的文件上传大小限制为2M,一般情况下,我们可以采用更改WEB.Config文 ...

  9. Asp.net mvc 大文件上传 断点续传

    Asp.net mvc 大文件上传 断点续传 进度条   概述 项目中需要一个上传200M-500M的文件大小的功能,需要断点续传.上传性能稳定.突破asp.net上传限制.一开始看到51CTO上的这 ...

随机推荐

  1. ansible七种武器和json

                                                               ansible七种武器和json • 第一种武器 – ansible 命令,用于执 ...

  2. json文件操作

    1.把字典或list转换成字符串方法 json.dumps() 2.把字符串转换成字典方法 json.loads() 3.indent 存储文件时每行加缩进数 4.ensere_asci 文件中有中文 ...

  3. es分页条数限制

    "error": { "root_cause": [ { "type": "query_phase_execution_excep ...

  4. tf.nn.softmax_cross_entropy_with_logits 分类

    tf.nn.softmax_cross_entropy_with_logits(logits, labels, name=None) 参数: logits:就是神经网络最后一层的输出,如果有batch ...

  5. .NET Core技术研究-主机

    前一段时间,和大家分享了 ASP.NET Core技术研究-探秘Host主机启动过程 但是没有深入说明主机的设计.今天整理了一下主机的一些知识,结合先前的博文,完整地介绍一下.NET Core的主机的 ...

  6. 【Java】【设计模式 Design Pattern】单例模式 Singleton

    什么是设计模式? 设计模式是在大量的实践中总结和理论化之后的最佳的类设计结构,编程风格,和解决问题的方式 设计模式已经帮助我们想好了所有可能的设计问题,总结在这些各种各样的设计模式当中,也成为GOF2 ...

  7. Thinking in Java,Fourth Edition(Java 编程思想,第四版)学习笔记(四)之Operators

    At the lowest level, data in Java is manipulated using operators Using Java Operators An operator ta ...

  8. 嘿嘿,我就知道面试官接下来要问我 ConcurrentHashMap 底层原理了,看我怎么秀他

    前言 上篇文章介绍了 HashMap 源码后,在博客平台广受好评,让本来己经不打算更新这个系列的我,仿佛被打了一顿鸡血.真的,被读者认可的感觉,就是这么奇妙. 然后,有读者希望我能出一版 Concur ...

  9. D. Ehab the Xorcist

    题意: 略: 感觉被演了一波,这是CFdiv2吗? 算是这个构造题吧. 1 首先我们可以将u进行二进制拆分来考虑.加入u>v那么小与v的那些数在怎么拼接也无法使异或值为u. 比如二进制U=1 0 ...

  10. 极验反爬虫防护分析之slide验证方式下图片的处理及滑动轨迹的生成思路

    本文要分享的内容是去年为了抢鞋而分析 极验(GeeTest)反爬虫防护的笔记,由于篇幅较长(为了多混点CB)我会按照我的分析顺序,分成如下四个主题与大家分享: 极验反爬虫防护分析之交互流程分析 极验反 ...