您能否通过参数和请求身份验证帮助我上传图片let username = "username"
let password = "password"
。
let kurl = "Server url"
let headers: HTTPHeaders = ["Authorization":"Basic \(base64EncodedCredential)"]
let parmeter = ["name":"taykun","is_user":"1"]
Alamofire.upload(multipartFormData: { (multipartFormData) in
}, to: kurl, encodingCompletion: { (result) in
})
用于请求身份验证
$("#material").select2({
tags: false,
minimumInputLength: 1, // Minimum Input length for search request
ajax: {
url:'actionName',
dataType:'json',
data:function(params){
return{
materialSearchTerm: params.term, // search term
page: params.page
};
},
processResults: function (data, page) {
var jsonResult = JSON.parse(data);
return {
results: jsonResult.result
};
}
}
});
答案 0 :(得分:0)
尝试使用此代码进行alamofire:
func uploadImageWithData(strApiUrl:String,strImageUrl:String,param:Dictionary<String, String>? = nil ,completionHandler: @escaping (_ result: NSDictionary) -> Void) -> Void{
Alamofire.upload(multipartFormData: { multipartFormData in
let urlImage:URL = URL.init(fileURLWithPath: strImageUrl)
multipartFormData.append(urlImage, withName: "your key for image use in API")
for (key, value) in param! {
multipartFormData.append(value.data(using:String.Encoding(rawValue: String.Encoding.utf8.rawValue))!, withName: key)
}
}, to: strApiUrl, encodingCompletion: {
(encodingResult) in
print("encoding result:\(encodingResult)")
switch encodingResult {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (Progress) in
print("Upload Progress: \(Progress.fractionCompleted)")
//send progress using delegate
})
upload.responseJSON{ (response) in }
case .failure(let encodingError):
print(encodingError)
}
})
}
func returnResponse (response: DataResponse<Any>)->NSDictionary
{
if (response.result.isSuccess)
{
if let value = response.result.value
{
return value as! NSDictionary
}
}
else
{
print("\(response.error?.localizedDescription)")
var statusCode = 0
if let error = response.result.error as? AFError {
statusCode = error._code // statusCode private
switch error {
case .invalidURL(let url):
print("Invalid URL: \(url) - \(error.localizedDescription)")
case .parameterEncodingFailed(let reason):
print("Parameter encoding failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
case .multipartEncodingFailed(let reason):
print("Multipart encoding failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
case .responseValidationFailed(let reason):
print("Response validation failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
switch reason {
case .dataFileNil, .dataFileReadFailed:
print("Downloaded file could not be read")
case .missingContentType(let acceptableContentTypes):
print("Content Type Missing: \(acceptableContentTypes)")
case .unacceptableContentType(let acceptableContentTypes, let responseContentType):
print("Response content type: \(responseContentType) was unacceptable: \(acceptableContentTypes)")
case .unacceptableStatusCode(let code):
print("Response status code was unacceptable: \(code)")
statusCode = code
}
case .responseSerializationFailed(let reason):
print("Response serialization failed: \(error.localizedDescription)")
print("Failure Reason: \(reason)")
// statusCode = 3840 ???? maybe..
}
print("Underlying error: \(error.underlyingError)")
} else if let error = response.result.error as? URLError {
print("URLError occurred: \(error)")
}else if let error = response.result.error as? NSError{
print("timeout")
statusCode = error._code
}else {
print("Unknown error: \(response.result.error)")
}
print(statusCode)
//make a response with nil value and set error or other information in it and return it.
let paramDic:NSMutableDictionary = NSMutableDictionary()
paramDic[KEY_MESSAGE] = response.error?.localizedDescription
paramDic[KEY_DATA] = nil
paramDic[KEY_STATUS_CODE] = "\(statusCode)"
paramDic[KEY_SUCCESS] = 0
return paramDic as NSDictionary
}
return NSDictionary()
}
以这种方式调用此方法:
let imgUrl = //first store your image locally and then set image url
var dicParam = Dictionary<String , String>()//your requestparameter dictionary
API.uploadImageWithData(strApiUrl: webserviceurl, strImageUrl: imgUrl, param: dicParam, completionHandler: { (result) in
print(result)
if result[KEY_SUCCESS] as! Int == 1{
//success
}else{
//fail
}
})