//上传图片的网络代码
var hoardingjson = { _id:id, populationincomegroup:incomeGroupArray, availablebydate:availDate, 标题:标题, 描述:desc, onemonthprice:oneMprice, 三个月价格:三个价格, 六个月价格:六个月价格, oneyearprice:oneYrprice, 地方:地方, streetname:streetName, trafficdensity:trafficDensity, populationcategory:populationDensity, ownername:ownerName, 移动:移动, leaseowner:currenrOwnerName, 长度:hoardingWidth, 广度:囤积高度, 纬度:纬度 经度:lon, registereddate:currentTimestamp, createdate:"", 更新:"", 状态:"", ownerid:ownerid };
var form_data = new FormData();
var imageCount = document.getElementById("editImages").files.length;
for (i = 0; i < imageCount; i++) {
form_data.append("file", document.getElementById("editImages").files[0]);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", server_url + "UpdateHoarding", true);
xhr.setRequestHeader("hoardingjson", JSON.stringify(hoardingjson));
xhr.send(form_data);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
success = true;
$("#updateHoardingModal").modal("hide");
alert("Hoarding is updated successfully");
location.href = "home.jsp";
}
}
}
Ios代码:
NSString * jsosSt = [self strOfthedata];
UIImage *imageOne = [UIImage imageNamed:@"edit.png"];
NSData *imageData1 = UIImageJPEGRepresentation(imageOne,0.6f);
NSString *fileName1 = [NSString stringWithFormat:@"%ld%c%c.jpeg", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a', arc4random_uniform(26) + 'a'];
NSDictionary * params = @ {@&#34; token&#34;:appdeligate.userInf.tokenId,@&#34; hoardingjson&#34;:[self strOfthedata]};
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:@"URL/CreateHoarding" parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[formData appendPartWithFileURL:[NSURL fileURLWithPath:savedImagePath] name:@"file" fileName:@"filename.jpg" mimeType:@"image/jpeg" error:nil];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSMutableString *strParams = [[NSMutableString alloc]init];
for (NSString *key in [params allKeys]) {
[strParams appendFormat:@"%@=%@", key, params[key]];
[strParams appendString:@"&"];
}
[strParams deleteCharactersInRange:NSMakeRange([strParams length]-1, 1)];
[request setHTTPBody:[strParams dataUsingEncoding:NSUTF8StringEncoding]];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
NSLog(@"%f",uploadProgress.fractionCompleted);
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"Error: %@", error);
} else {
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
答案 0 :(得分:0)
------------这对我有用---------------
-(void)UploadImagewithUrl:(NSString *)serviceURL
withJson:(NSString *)jsonStr
withtoken:(NSString *)Token_id
withImageArray:(NSArray *)imageURlArray
callback:(SuccessCallback)callback
failerCallback:(FailureCallback)failercallback {
NSString *baserl=[NSString stringWithFormat:@"%@?token=%@&hoardingjson=%@",serviceURL,Token_id,jsonStr];
baserl = [baserl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSString *lineEnd = @"\r\n";
NSString* twoHyphens = @"--";
NSString* boundary = @"*****";
NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:baserl parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
[request addValue:contentType forHTTPHeaderField: @"Content-Type"];
for (int i=0; i<imageURlArray.count; i++) {
NSData *imageData = [[NSFileManager defaultManager] contentsAtPath:[imageURlArray objectAtIndex:i]];
NSString *fileName = [NSString stringWithFormat:@"%ld%c.jpeg", (long)[[NSDate date] timeIntervalSince1970], arc4random_uniform(26) + 'a'];
[formData appendPartWithFormData:[twoHyphens dataUsingEncoding:NSUTF8StringEncoding] name:@"twoHyphens"];
[formData appendPartWithFormData:[boundary dataUsingEncoding:NSUTF8StringEncoding]
name:@"boundary"];
[formData appendPartWithFormData:[lineEnd dataUsingEncoding:NSUTF8StringEncoding]
name:@"lineEnd"];
[formData appendPartWithFileData:imageData
name:@"file"
fileName:fileName
mimeType:@"image/jpeg"];
}
[formData appendPartWithFormData:[lineEnd dataUsingEncoding:NSUTF8StringEncoding] name:@"lineEnd"];
[formData appendPartWithFormData:[twoHyphens dataUsingEncoding:NSUTF8StringEncoding] name:@"twoHyphens"];
[formData appendPartWithFormData:[boundary dataUsingEncoding:NSUTF8StringEncoding]
name:@"boundary"];
[formData appendPartWithFormData:[lineEnd dataUsingEncoding:NSUTF8StringEncoding]
name:@"lineEnd"];
} error:nil];
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
NSURLSessionUploadTask *uploadTask;
uploadTask = [manager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
// This is not called back on the main queue.
[SVProgressHUD showProgress:uploadProgress.fractionCompleted status:@"Uploading"];
if (uploadProgress.fractionCompleted==1)
{
[SVProgressHUD dismiss];
}
// You are responsible for dispatching to the main queue for UI updates
dispatch_async(dispatch_get_main_queue(), ^{
//Update the progress view
[progressView setProgress:uploadProgress.fractionCompleted];
NSLog(@"---response---- %@",uploadProgress);
});
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
failercallback([NSString stringWithFormat:@"%ld",error.code],@"failer");
NSLog(@"Error: %@", error);
} else {
callback(YES,responseObject);
NSLog(@"%@ %@", response, responseObject);
}
}];
[uploadTask resume];
}
答案 1 :(得分:0)
这是使用AFNetworking
AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:stringURL]];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager POST:stringURL parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData)
{
//do not put image inside parameters dictionary as I did, but append it!
[formData appendPartWithFileData:nsdataFromBase64String name:@"" fileName:@"" mimeType:@"image/jpeg"];
}
success:^(NSURLSessionDataTask *task, id responseObject)
{
//here is place for code executed in success case
}
failure:^(NSURLSessionDataTask *task, NSError *error)
{
//here is place for code executed in error case
}];