在php
:
Upload
方法:
/**
* ### this function is file upload
* auto file name and file path
* @param $FILES File to file
* @param string $A
* @param string $B
* @return bool|string
*/
protected function Upload($FILES,$A="",$B=""){
$ReturnFILE = array();
$FILES = array_keys($FILES);
foreach ($FILES as $K => $V) {
$FlodName = "Updata/".date("Y-m-d");
if(!is_dir($FlodName)){
mkdir($FlodName,777,true);
}
if ($_FILES[$FILES[$K]]["error"] > 0){
return false;
}
$tempEXT = strstr($_FILES[$FILES[$K]]["name"],".");
$FileName = date("YmdHis").UUID().$tempEXT;
move_uploaded_file($_FILES[$FILES[$K]]["tmp_name"],"{$FlodName}/" . $FileName);
$http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
$FileName =$http_type.$_SERVER['HTTP_HOST']."/".$FlodName."/".$FileName;
$ReturnFILE[] = $FileName;
}
return $ReturnFILE;
}
ImageEdit
方法使用Upload
方法上传iOS应用旁路图片:
public function ImgEdit()
{
$imgs=$this->Upload($_FILES);
var_dump($imgs);
// success
if (!empty($imgs)){
echo 1;
$datas = [
'code' => 200,
'message' => "修改成功",
'data' =>$imgs
];
echo json_encode($datas);
} else { // fail
echo 2;
$datas = [
'code' => 0,
'message' => "修改失败",
'data' => ""
];
echo json_encode($datas);
}
}
在iOS应用中,我使用此方法上传我的图片:
- (void)networkUploadHeadImage:(UIImage *)image {
UIImage *img = image;
NSData *dataObj = UIImagePNGRepresentation(img);
NSDictionary * param1 = @{
@"imgFile":dataObj
};
AFHTTPSessionManager * session = [AFHTTPSessionManager manager];
session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json",@"application/xml",@"text/json",@"text/javascript",@"text/html",@"text/plain",@"multipart/form-data",nil];
//拼接地址
NSString *url = @"http://103.71.178.145:8088/Home/Aboutus/ImgEdit";
[session POST:url parameters:param1 constructingBodyWithBlock:^(id<AFMultipartFormData> _Nonnull formData) {
UIImage *img = image; // response
NSData *data = UIImagePNGRepresentation(img);
[formData appendPartWithFileData:data name:@"imgFile" fileName:@"imgFile.png"mimeType:@"image/png"];
} success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject) {
NSLog(@"success+%@", responseObject);
//保存
NSString *result_url_str = responseObject[@"data"];
} failure:^(NSURLSessionDataTask * _Nonnull task, NSError * _Nonnull error) {
NSLog(@"fail");
}];
}
结果是:
如果我使用iOS方法上传我的图片:
数据库我们可以看到上传的图片,但是成功了,但在ImageEdit
方法中,$imgs
为空:
var_dump($imgs); the `$imgs` is empty.
我的iOS应用执行:NSLog(@"fail");
如果我使用html表单提交:
<html>
<body>
<form action="Insert" method="post"
enctype="multipart/form-data">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>
</body>
</html>
我会得到$imgs
,它有上传图片的路径。
为什么我使用- (void)networkUploadHeadImage:(UIImage *)image
对$imgs
一无所知?
修改
如果我使用KK的答案:
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@",BASEURL,url] parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (image) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:@"imagename" fileName:@"Image.jpg" mimeType:@"image/jpeg"];
}
}error:nil];
AFURLSessionManager * urlSessionmanager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
urlSessionmanager.responseSerializer = [AFJSONResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [urlSessionmanager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"error:%@", error);
} else {
// successfully uploaded
}
}];
[uploadTask resume];
我将打印错误信息:
错误Domain = com.alamofire.error.serialization.response Code = -1016&#34;请求失败:不可接受的内容类型:text / html&#34; UserInfo = {com.alamofire.serialization.response.error.response = {URL:http://103.71.178.145:8088/Home/Aboutus/ImgEdit} {status code:200,headers { &#34;缓存控制&#34; =&#34; no-store,no-cache,must-revalidate,post-check = 0,pre-check = 0&#34 ;; &#34; Content-Length的&#34; = 239; &#34;内容类型&#34; =&#34; text / html; charset = utf8&#34 ;; 日期=&#34;周一,2017年4月17日11:18:20 GMT&#34 ;; Expires =&#34; Thu,1981年11月19日08:52:00 GMT&#34 ;; Pragma =&#34; no-cache&#34 ;; Server =&#34; Microsoft-IIS / 7.5&#34 ;; &#34;的Set-Cookie&#34; =&#34; PHPSESSID = a5n20to0r0ahk554ppa79jfp56;路径= /&#34 ;; &#34; X供电-通过&#34; =&#34; PHP / 5.4.33,ASP.NET&#34 ;; }},NSErrorFailingURLKey = http://103.71.178.145:8088/Home/Aboutus/ImgEdit,com.alamofire.serialization.response.error.data = LT; 0d0a3231 6e676e67 32617272 61792831 29207b0a 20205b30 5d3d3e0a 20207374 72696e67 28363329 20226874 74703a2f 2f313033 2e37312e 3137382e 3134353a 38303838 2f557064 6174612f 32303137 2d30342d 31372f32 30313730 34313731 39313832 302e6a70 67220a7d 0a317b22 636f6465 223a3230 302c226d 65737361 6765223a 225c7534 6665655c 75363533 395c7536 3231305c 75353239 66222c22 64617461 223a5b22 68747470 3a5c2f5c 2f313033 2e37312e 3137382e 3134353a 38303838 5c2f5570 64617461 5c2f3230 31372d30 342d3137 5c2f3230 31373034 31373139 31383230 2e6a7067 225d7d&gt;中NSLocalizedDescription =请求失败:不可接受的内容类型:文本/ HTML }
但是,如果我上传像KK这样的更新方法:
UIImage *img = image;
NSData *dataObj = UIImagePNGRepresentation(img);
NSString *url = @"http://103.71.178.145:8088/Home/Aboutus/ImgEdit";
NSDictionary * param1 = @{
@"imgFile":dataObj
};
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:url parameters:param1 constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (image) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:@"imagename" fileName:@"Image.jpg" mimeType:@"image/jpeg"];
}
}error:nil];
AFURLSessionManager * urlSessionmanager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
urlSessionmanager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [urlSessionmanager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
NSLog(@"err=%@", error);
} else {
// successfully uploaded
NSLog(@"success= %@, === %@", response, responseObject);
}
}];
[uploadTask resume];
虽然我成功了,但没有得到返回网址,但PHP没有向我返回网址(图片的路径)。
请参阅我的日志:
2017-04-17 19:34:50.058 uploadImgTool [73016:16061592] success = {URL:http://103.71.178.145:8088/Home/Aboutus/ImgEdit} {status code:200,headers { &#34;缓存控制&#34; =&#34; no-store,no-cache,must-revalidate,post-check = 0,pre-check = 0&#34 ;; &#34; Content-Length的&#34; = 232; &#34;内容类型&#34; =&#34; text / html; charset = utf8&#34 ;; 日期=&#34;周一,2017年4月17日11:34:24 GMT&#34 ;; Expires =&#34; Thu,1981年11月19日08:52:00 GMT&#34 ;; Pragma =&#34; no-cache&#34 ;; Server =&#34; Microsoft-IIS / 7.5&#34 ;; &#34;的Set-Cookie&#34; =&#34; PHPSESSID = 1qqv4nnp5gf5o8nqcuhve12ds2;路径= /&#34 ;; &#34; X供电-通过&#34; =&#34; PHP / 5.4.33,ASP.NET&#34 ;; }},===&LT; 0d0a6172 72617928 3129207b 0a20205b 305d3d3e 0a202073 7472696e 67283633 29202268 7474703a 2f2f3130 332e3731 2e313738 2e313435 3a383038 382f5570 64617461 2f323031 372d3034 2d31372f 32303137 30343137 31393334 32342e6a 7067220a 7d0a317b 22636f64 65223a32 30302c22 6d657373 61676522 3a225c75 34666565 5c753635 33395c75 36323130 5c753532 3966222c 22646174 61223a5b 22687474 703a5c2f 5c2f3130 332e3731 2e313738 2e313435 3a383038 385c2f55 70646174 615c2f32 3031372d 30342d31 375c2f32 30313730 34313731 39333432 342e6a70 67225d7d&gt;
答案 0 :(得分:1)
尝试使用我的代码段下方上传图片。
NSMutableURLRequest *request = [[AFHTTPRequestSerializer serializer] multipartFormRequestWithMethod:@"POST" URLString:[NSString stringWithFormat:@"%@%@",BASEURL,url] parameters:parameter constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
if (image) {
[formData appendPartWithFileData:UIImageJPEGRepresentation(image, 0.8) name:@"imagename" fileName:@"Image.jpg" mimeType:@"image/jpeg"];
}
}error:nil];
AFURLSessionManager * urlSessionmanager = [[AFURLSessionManager alloc] initWithSessionConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration]];
urlSessionmanager.responseSerializer = [AFHTTPResponseSerializer serializer];
NSURLSessionUploadTask *uploadTask;
uploadTask = [urlSessionmanager
uploadTaskWithStreamedRequest:request
progress:^(NSProgress * _Nonnull uploadProgress) {
}
completionHandler:^(NSURLResponse * _Nonnull response, id _Nullable responseObject, NSError * _Nullable error) {
if (error) {
} else {
// successfully uploaded
}
}];
[uploadTask resume];