在同一POST中上传图像和其他数据 [英] Upload image along with other data in same POST
问题描述
我想使用POST方法上传图片。我可以单独上传图片。但我想将它们与我需要发送的其他数据一起发布到服务器。任何人都可以帮助我。知道如何发布
I want to upload image using POST method. I can upload the image separately. But I want to post them to the server along with other data which I need to send. Can anyone please help me.know how to post
以下是我发送数据的代码。除此之外,我需要将图像与此一起发送
Here is the code where I send my data. Along with this,I need to send the image along with this
postString = [NSString stringWithFormat:@"u=TuNmae&p=pass&o=onr&j=123&a=321&d=8765&t=123&at=need&image="];
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url1];
NSString *msgLength = [NSString stringWithFormat:@"%d", [postString length]];
[req addValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[req addValue:msgLength forHTTPHeaderField:@"Content-Length"];
[req setHTTPMethod:@"POST"];
[req setHTTPBody: [postString dataUsingEncoding:NSUTF8StringEncoding]];
NSData *returnData = [NSURLConnection sendSynchronousRequest:req returningResponse:nil error:nil];
webData = [[NSMutableData data] retain];
[webData appendData:returnData];
NSLog(@"attempt%@",webData);
NSString *webResult;
webResult = [[NSString alloc] initWithData:webData encoding:NSASCIIStringEncoding];
webResult = [webResult stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSLog(@"str %@",webResult);
我需要将图像插入到postString中。最后一个参数。
I need to insert the image into the postString. The last parameter.
推荐答案
您必须将enctype表单属性设置为multipart / form-data
You must set the enctype form atribute to "multipart/form-data"
表格enctype =multipart / form-data
然后你可以上传文件输入和其他文字或隐藏输入以相同的
格式提供相同的提交。
then you can upload file input and other text or hidden input in same form adn same submit.
在你的api中这样做
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@",boundary];
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
//file data
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *fullPathToFile = [documentsDirectory stringByAppendingPathComponent:@"ImageFile.png"];
NSData *imageData = [[NSData alloc] initWithContentsOfFile:fullPathToFile];
这篇关于在同一POST中上传图像和其他数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!