File Upload Download For iOS

 

本文內容來自於王志剛 《軟件創富密碼:iPhone應用程序開發攻略之深刻淺出Objective-C 2.0》一書,修改了部份內容。php

截圖以下:html

Download:api

代碼以下:服務器

//
//  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不同:app

<?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' );
?>

 

ui

相關文章
相關標籤/搜索