我想使用Web服务将所选图像从图像查看器上载到服务器。将图像文件上传到服务器时出错
我的web服务需要用户ID,密码和文件名作为请求。
但是当我运行时,我得到错误的文件名。
错误显示“过程需要未提供的文件名”。虽然我在这里传递文件名。
任何人都可以看看代码,让我知道,可能是什么问题? - 谢谢。
NSData *imageData;
imageData = UIImageJPEGRepresentation(imageView.image, 90);
//creating the url request:
NSURL *postUrl = [NSURL URLWithString:@"myURL"];
NSMutableURLRequest *postRequest = [NSMutableURLRequest requestWithURL:postUrl];
//adding header information:
[postRequest setHTTPMethod:@"POST"];
NSString *stringBoundary = [NSString stringWithString:@"0xKhTmLbOuNdArY"];
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",stringBoundary];
[postRequest addValue:contentType forHTTPHeaderField: @"Content-Type"];
//setting up the body:
NSMutableData *postBody = [NSMutableData data];
[postBody appendData:[[NSString stringWithFormat:@"--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"userid\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:@"100"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"pwd\"\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:@"pwd"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:@"Content-Disposition: form-data; name=\"image\"; filename=\"1.jpg\"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:@"Content-Type: image/jpg\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[[NSString stringWithString:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
[postBody appendData:[NSData dataWithData:imageData]];
[postBody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",stringBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
[postRequest setHTTPBody:postBody];
// now lets make the connection to the web
NSData *returnData = [NSURLConnection sendSynchronousRequest:postRequest returningResponse:nil error:nil];
NSString *returnString;
returnString = [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
lblLoginStatus.text = @"Uploading done.";
NSLog(@"%@",returnString);
我只是花了几天的时间尝试将图片上传到服务器上,实际上有很多变量。这可能是服务器端而不是iOS端的问题。 我可以推荐几件事吗? 1.注释掉以下行: [postBody appendData:[[NSString stringWithString:@“Content-Type:image/jpg \ r \ n \ r \ n”] dataUsingEncoding:NSUTF8StringEncoding]]; 2.添加内容长度: [请求addValue:[NSString stringWithFormat:@“%d”,[body length]] forHTTPHeaderField:@“Content-Length”]; – John