您的位置:首页 > 理论基础 > 计算机网络

iOS Asihttp上传文件(图片等)以及服务端的代码(c#,.net Web api2)

2014-11-26 16:21 465 查看
1,客户端的代码
NSString *api = @"http://192.168.20.189:6900/bk/api/upload";
ASIFormDataRequest *req = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:api]];
[req setRequestMethod:@"POST"];

//    NSString *imgPath = @"/Users/duanhai/Desktop/test.png";
NSString *path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@".png"];
//  NSData *image = [[NSData alloc] initWithContentsOfFile:path];
//    [req addData:image withFileName:@"test.png" andContentType:@"image/jpeg" forKey:@"image"];
[req setFile:path forKey:@"whatever"];
[req setCompletionBlock:^{
NSLog(@"xxxx is %@ and err is %@",req.responseString,req.error);
}];
[req setFailedBlock:^{
NSLog(@"err code is %@",[req.error localizedDescription]);
}];
[req startAsynchronous];
2,服务端代码
 [RoutePrefix("api/upload")]public class UploadController : ApiController{public HttpResponseMessage Post(){HttpResponseMessage result = null;var httpRequest = HttpContext.Current.Request;if (httpRequest.Files.Count > 0){var docfiles = new List<string>();foreach (string file in httpRequest.Files){var postedFile = httpRequest.Files[file];// var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);var filePath = "C:/Users/Tony_mac/Desktop/upload/"+postedFile.FileName;postedFile.SaveAs(filePath);docfiles.Add(filePath);}result = Request.CreateResponse(HttpStatusCode.Created, docfiles);}else{result = Request.CreateResponse(HttpStatusCode.BadRequest);}return result;}}
服务端我是建了一个虚拟目录,故api地址中有个bk。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: