iOS-通过HTTP POST上载图像
目标:我想通过HTTP POST方法将图像(UIImage)上传到服务器 问题:我收到一个响应“您没有选择要上载的文件。”(状态=200) 提示:以下是Android应用程序的java代码:iOS-通过HTTP POST上载图像,ios,objective-c,post,uiimage,Ios,Objective C,Post,Uiimage,目标:我想通过HTTP POST方法将图像(UIImage)上传到服务器 问题:我收到一个响应“您没有选择要上载的文件。”(状态=200) 提示:以下是Android应用程序的java代码: public static String sendImage(String url, String username, String password, String filePath) { try { File file = new File(filePath);
public static String sendImage(String url, String username, String password, String filePath) {
try {
File file = new File(filePath);
int fileSize = (int) (file.length() / 1024);
if (fileSize < 2048 && fileSize > 0) {
HttpClient httpClient = new DefaultHttpClient();
AuthScope authScope = new AuthScope(HOST, 80);
UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(username, password);
((AbstractHttpClient) httpClient).getCredentialsProvider().setCredentials(authScope, usernamePasswordCredentials);
BasicHttpContext localHttpContext = new BasicHttpContext();
BasicScheme basicScheme = new BasicScheme();
localHttpContext.setAttribute("preemptive-auth", basicScheme);
HttpHost targetHttpHost = new HttpHost(HOST, 80, "http");
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("enctype", "multipart/form-data");
MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
multipartEntity.addPart("userfile", new FileBody(file));
httpPost.setEntity(multipartEntity.build());
HttpResponse httpResponse = httpClient.execute(targetHttpHost, httpPost, localHttpContext);
int statusCode = httpResponse.getStatusLine().getStatusCode();
String reason = httpResponse.getStatusLine().getReasonPhrase();
Log.d(TAG, "Status code: " + statusCode + " " + reason + "\n" + EntityUtils.toString(httpResponse.getEntity()));
return "Status code: " + statusCode + " " + reason;
} else {
return "Please select image smaller than 200 kB";
}
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.toString());
}
return null;
}
您可以使用下面的代码上传图像
-(void)uploadPhotoToUserWithID:(int)userid photo:(UIImage *)loginpic
{
NSString *urlstr = [NSString stringWithFormat:@"http://XXX:XXX@example.com/upload/id/89"];
NSURL *url = [NSURL URLWithString:urlstr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"----WebKitFormBoundarycC4YiaUFwM44F6rT";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSData *imageData;
imageData = UIImageJPEGRepresentation(loginpic, 0.2f);
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
if(appDelegate.isPhototaken)
{
[body appendData:[@"Content-Disposition: form-data; name=\"profilepic.jpeg\"; filename=\"picture.jpeg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// We now need to tell the receiver what content type we have
// In my case it's a png image. If you have a jpg, set it to 'image/jpg'
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
else
{
[body appendData:[@"Content-Disposition: form-data; name=\"profilepic.png\"; filename=\"picture.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// We now need to tell the receiver what content type we have
// In my case it's a png image. If you have a jpg, set it to 'image/jpg'
[body appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
// Now we append the actual image data
[body appendData:[NSData dataWithData:imageData]];
// and again the delimiting boundary
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSDictionary *dict;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
[body appendData:jsonData];
[request setHTTPBody:body];
urlconnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
respData = [[NSMutableData alloc] init];
NSLog(@"@@@@@@@@@Data is:%@",response);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[respData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *errInfo;
NSDictionary *mainDict= [NSJSONSerialization JSONObjectWithData:respData options:kNilOptions error:&errInfo];
NSLog(@"maindictionary is %@",mainDict);
NSError *jsonParsingError = nil;
id object = [NSJSONSerialization JSONObjectWithData:respData options:0 error:&jsonParsingError];
if (jsonParsingError)
{
NSLog(@"JSON ERROR: %@", [jsonParsingError localizedDescription]);
}
else
{
NSLog(@"OBJECT: %@", [object class]);
}
}
希望它能帮助你 …这是干什么用的<代码>NSDictionary*dict;NSData*jsonData=[NSJSONSerialization dataWithJSONObject:dict选项:0错误:NULL];[正文数据:jsonData]代码>我想我会在字典里得到答案..所以我这样写。根据您的要求更改代码。。你在NSLog上有什么发现吗数据是..我解决了。问题很简单-我为
enctype
设置了多部分/表单数据,而不是内容类型
,谢谢。您也可以使用我的代码上传图像。如果我的回答对你的问题有帮助或与你的问题相关,请接受我的回答。。
-(void)uploadPhotoToUserWithID:(int)userid photo:(UIImage *)loginpic
{
NSString *urlstr = [NSString stringWithFormat:@"http://XXX:XXX@example.com/upload/id/89"];
NSURL *url = [NSURL URLWithString:urlstr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:60.0];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"----WebKitFormBoundarycC4YiaUFwM44F6rT";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];
NSMutableData *body = [NSMutableData data];
NSData *imageData;
imageData = UIImageJPEGRepresentation(loginpic, 0.2f);
[body appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
if(appDelegate.isPhototaken)
{
[body appendData:[@"Content-Disposition: form-data; name=\"profilepic.jpeg\"; filename=\"picture.jpeg\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// We now need to tell the receiver what content type we have
// In my case it's a png image. If you have a jpg, set it to 'image/jpg'
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
else
{
[body appendData:[@"Content-Disposition: form-data; name=\"profilepic.png\"; filename=\"picture.png\"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
// We now need to tell the receiver what content type we have
// In my case it's a png image. If you have a jpg, set it to 'image/jpg'
[body appendData:[@"Content-Type: image/png\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
}
// Now we append the actual image data
[body appendData:[NSData dataWithData:imageData]];
// and again the delimiting boundary
[body appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n",boundary] dataUsingEncoding:NSUTF8StringEncoding]];
NSDictionary *dict;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:0 error:NULL];
[body appendData:jsonData];
[request setHTTPBody:body];
urlconnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
respData = [[NSMutableData alloc] init];
NSLog(@"@@@@@@@@@Data is:%@",response);
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[respData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSError *errInfo;
NSDictionary *mainDict= [NSJSONSerialization JSONObjectWithData:respData options:kNilOptions error:&errInfo];
NSLog(@"maindictionary is %@",mainDict);
NSError *jsonParsingError = nil;
id object = [NSJSONSerialization JSONObjectWithData:respData options:0 error:&jsonParsingError];
if (jsonParsingError)
{
NSLog(@"JSON ERROR: %@", [jsonParsingError localizedDescription]);
}
else
{
NSLog(@"OBJECT: %@", [object class]);
}
}