GOAL :我想通过HTTP POST方法将图片( UIImage )上传到服务器。
问题:我收到回复" 您没有选择要上传的文件。" (状态= 200)
提示:以下是来自Android应用程序的java代码:
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 *)photo
{
// Convert UIImage to JPEG
NSData *imageData = UIImageJPEGRepresentation(photo, 0.5);
// Create request
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"http://XXX:XXX@example.com/upload/id/89"]];
[request setCachePolicy:NSURLRequestReloadIgnoringLocalCacheData];
[request setHTTPShouldHandleCookies:NO];
[request setTimeoutInterval:30];
[request setHTTPMethod:@"POST"];
NSString *boundary = @"unique-consistent-string";
// Post body
NSMutableData *body = [[NSMutableData alloc] init];
// Add image data
if (imageData)
{
[body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=%@; filename=\"imageName.jpg\"\r\n", @"\"userfile\""] dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:[@"Content-Type: image/jpeg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
[body appendData:imageData];
[body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
// Setting the body of the post to the reqeust
[request setHTTPBody:body];
// Set Content-Type in HTTP header
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField: @"enctype"];
NSString *postLength = [NSString stringWithFormat:@"%d", body.length];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if(data.length > 0)
{
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
NSLog(@"%i", httpResponse.statusCode);
}
}];
}
答案 0 :(得分:1)
您可以使用以下代码上传图片..
-(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]);
}
}
希望它可以帮助你......!