File Upload Download For iOS

 

本文内容来自于王志刚 《软件创富密码:iPhone应用程序开发攻略之深入浅出Objective-C 2.0》一书,修改了部分内容。

截图如下:

Download:

代码如下:

//
//  AppController.h
//  File Upload Download
//
//  Created by longx-app on 13-9-15.
//  Copyright (c) 2013年 longx-app. All rights reserved.
//

#import <Foundation/Foundation.h>

@interface AppController : NSObject <NSURLConnectionDataDelegate>
{
    NSMutableData *m_data;  // 图片数据
    BOOL m_is_upload;       // 上传标志
    NSString *action_type;   // 操作类型
    NSMutableData *m_result; // 返回数据
}

@property (strong, nonatomic) IBOutlet UIImageView *imageView;

- (IBAction)upload:(id)sender;
- (IBAction)download:(id)sender;

@end

 

//
//  AppController.m
//  File Upload Download
//
//  Created by longx-app on 13-9-15.
//  Copyright (c) 2013年 longx-app. All rights reserved.
//

#import "AppController.h"

@implementation AppController

@synthesize imageView=_imageView;

- (id)init
{
    if (self = [super init]) { // equivalent to "self does not equal nil"
        m_is_upload = TRUE;
    }
    return self;
}

- (IBAction)upload:(id)sender
{
    action_type = @"UPLOAD";
    
    if (m_data == nil) {
        return;
    }
    // 上传的情况下
    if (m_is_upload) {
        m_is_upload = FALSE;
        //m_data = [[NSMutableData data] retain];
        m_result = [[NSMutableData data] retain];
        
        NSData *pData = UIImagePNGRepresentation([_imageView image]);
        [self uploadPictureProcess:pData];

        return;
    }
    
    return;
}

- (IBAction)download:(id)sender
{
    action_type = @"DOWNLOAD";
    
    m_data = [[NSMutableData data] retain];
    // 请求
    NSString *url = @"http://coolapp-image.stor.sinaapp.com/orginal.png";
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    if (con == NULL) {
        return;
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    if ([action_type isEqualToString:@"DOWNLOAD"]) {
        // 追加接收的数据
        [m_data appendData:data];
    }
    else if ([action_type isEqualToString:@"UPLOAD"])
    {
        // 追加数据
        [m_result appendData:data];
    }
}

// 结束网络连接
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    
    if ([action_type isEqualToString:@"DOWNLOAD"])
    {
        UIImage *img = [[UIImage alloc] initWithData:m_data];
        [_imageView setImage:img];
    }
    else if ([action_type isEqualToString:@"UPLOAD"])
    {
        NSLog(@"Upload finish!!");
        m_is_upload = TRUE;
        // 打印结果
        NSMutableString *result = [[NSMutableString alloc] initWithData:m_result encoding:NSUTF8StringEncoding];
        NSLog(@"%@", [NSString stringWithString:result]);
        m_result = nil;
    }
}

// 上传图片
- (void)uploadPictureProcess:(NSData*)imgData {
    //UIApplication *app = [UIApplication sharedApplication];
    // 初始化
    // 连接设置,创建request对象
    NSString *url = @"http://1.coolapp.sinaapp.com/uploadpicture.php";
    NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:url] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:30.0];
    // 进行HTTP头设置,首先设置主机,接着设置用户代理、语言和文字编码等。中文环境下必须GB2312或者UTF-8
    [req addValue:[NSString stringWithFormat:@"1.coolapp.sinaapp.com"] forHTTPHeaderField:@"Host"];
    [req addValue:[NSString stringWithFormat:@"Mozilla/5.0 (iPod; U; CPU iPhone OS 4_3 like Mac OS X; zh-Hans)"] forHTTPHeaderField:@"User-Agent"];
    [req addValue:[NSString stringWithFormat:@"text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"] forHTTPHeaderField:@"Accept"];
    [req addValue:[NSString stringWithFormat:@"zh,en-us;q=0.7,en;q=0.3"] forHTTPHeaderField:@"Accept-Language"];
    [req addValue:[NSString stringWithFormat:@"gzip,deflate"] forHTTPHeaderField:@"Accept-Encoding"];
    [req addValue:[NSString stringWithFormat:@"gb2312,utf-8;q=0.7,*;q=0.7"] forHTTPHeaderField:@"Accept-Charset"];
    [req addValue:[NSString stringWithFormat:@"300"] forHTTPHeaderField:@"Keep-Alive"];
    [req addValue:[NSString stringWithFormat:@"keep-alive"] forHTTPHeaderField:@"Connection"];
    [req addValue:[NSString stringWithFormat:@"max-age=0"] forHTTPHeaderField:@"Cache-Control"];
    
    // 将HTTP方法设置POST
    [req setHTTPMethod:@"POST"];
    
    // 设置内容类型,注意必须是“multipart/form-data; boundary=XX”与form表单中上传文件的设置一样。
    NSString    *boundary = [NSString stringWithFormat:@"---------------------------12345678912345678912345678912"];
    NSString    *content_type = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [req addValue:content_type forHTTPHeaderField:@"Content-Type"];
    
    // 主体(Body)
    NSMutableData *body = [[NSMutableData data] retain];
    // 注意中文环境中必须使用NSUTF8StringEncoding
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"up\"; filename=\"test.png\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    //将主体(body)的内容类型设置为“image/png”,如果是JPEG图片则为“image/jpeg”。
    [body appendData:[[NSString stringWithFormat:@"Content-Type: image/png\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
    //追加图片数据
    [body appendData:imgData];
    [body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [req setHTTPBody:body];
    
    // 服务器连接开始
    NSURLConnection *con = [[NSURLConnection alloc] initWithRequest:req delegate:self];
    if(con == NULL){
        return;
    }
}
@end

 

PHP服务器端代码如下:

因为服务器使用新浪云服务器,所以有些api不一样:

<?php

// 保存接收图片
// var_dump($_FILES['up']['tmp_name']);
if ($_FILES['up']['tmp_name']) {
    file_put_contents( SAE_TMP_PATH . '/test.png' , file_get_contents($_FILES['up']['tmp_name']) );
    
    $s = new SaeStorage();
    $s->upload( 'image' , 'remote_test_file.png' , SAE_TMP_PATH . '/test.png' );
    echo "OK";
} else {
    echo "NG";
}


//file_put_contents( SAE_TMP_PATH . '/mycode.txt' , 'dummy test' );
//echo file_get_contents( SAE_TMP_PATH . '/mycode.txt' ); // will echo dummy test;
//
//$s = new SaeStorage();
//$s->upload( 'resources' , 'remote_file.txt' , SAE_TMP_PATH . '/mycode.txt' );
?>

 

posted on 2013-09-15 22:22  loveq369 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/loveq/p/3323348.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值