iOS Asihttp上傳文件(圖片等)以及服務端的代碼(c#,.net Web api2)

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。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章