
# 文件上传
#### 前提条件
使用SDK管理OBS资源，您需要先根据[SDK下载](https://support.huaweicloud.com/sdk-ios-devg-obs/obs_27_0001.html)了解并选择合适的SDK版本，然后下载SDK并完成安装。
#### 示例代码
文件上传使用本地文件作为对象的数据源。以下代码展示了如何进行文件上传：
```
static OBSClient *client;
NSString *endPoint = @"https://your-endpoint";
// 认证用的ak和sk硬编码到代码中或者明文存储都有很大的安全风险，建议在配置文件或者环境变量中密文存放，使用时解密，确保安全；本示例以ak和sk保存在环境变量中为例，运行本示例前请先在本地环境中设置环境变量AccessKeyID和SecretAccessKey。
// 您可以登录访问管理控制台获取访问密钥AK/SK，获取方式请参见https://support.huaweicloud.com/usermanual-ca/ca_01_0003.html
char* ak_env = getenv("AccessKeyID");
char* sk_env = getenv("SecretAccessKey");
if (ak_env == NULL || sk_env == NULL) {
    NSLog(@"Error: AccessKeyID or SecretAccessKey environment variable not set");
    return;
}
NSString *AK = [NSString stringWithUTF8String:ak_env];
NSString *SK = [NSString stringWithUTF8String:sk_env];
// 初始化身份验证
OBSStaticCredentialProvider *credentialProvider = [[OBSStaticCredentialProvider alloc] initWithAccessKey:AK secretKey:SK];
    
//初始化服务配置
OBSServiceConfiguration *conf = [[OBSServiceConfiguration alloc] initWithURLString:endPoint credentialProvider:credentialProvider];
    
// 初始化client
client = [[OBSClient alloc] initWithConfiguration:conf];
//指定待上传文件名及文件类型
NSString *filePath = [[NSBundle mainBundle]pathForResource:@"fileName" ofType:@"Type"];
// 文件上传
OBSPutObjectWithFileRequest *request = [[OBSPutObjectWithFileRequest alloc]initWithBucketName:@"bucket-ios-test02" objectKey:@"imageWithFile" uploadFilePath:filePath];
// 开启后台上传，当应用退出到后台后，上传任务仍然会进行
request.background = YES; 
    
// 上传进度
request.uploadProgressBlock = ^(int64_t bytesSent, int64_t totalBytesSent, int64_t totalBytesExpectedToSend) {
    NSLog(@"%0.1f%%",(float)floor((totalBytesExpectedToSend > 0) ? (totalBytesSent*10000/totalBytesExpectedToSend) : 0)/100);
};
    
[client putObject:request completionHandler:^(OBSPutObjectResponse *response, NSError *error){
    // 判断error状态
    if(error){
        // 打印错误信息 
        NSLog(@"文件上传失败");
        NSLog(@"%@",error);
    }
    // 上传文件成功，返回200，打印返回响应值 
    if([response.statusCode isEqualToString:@"200"]){
        NSLog(@"文件上传成功");
        NSLog(@"%@",response);
        if(response.etag){NSLog(@"%@",response.etag);}
    } 
}];
```
![](https://support.huaweicloud.com/sdk-ios-devg-obs/public_sys-resources/notice_3.0-zh-cn.png)
当前SDK的文件上传接口（OBSPutObjectWithFileRequest、OBSUploadFileRequest）的uploadFilePath参数仅接受NSString类型的文件路径，不支持直接传入\[NSURL fileURLWithPath:@"xxx"\]构造的NSURL对象。如需使用NSURL，请先通过\[fileURL path\]获取文件路径字符串，再传入uploadFilePath参数。
![](https://support.huaweicloud.com/sdk-ios-devg-obs/public_sys-resources/note_3.0-zh-cn.png)
上传的内容大小不能超过5GB。
设置background为YES时，可以开启后台上传。
