通过 HTTP $_POST 快速上传图片
Posted
技术标签:
【中文标题】通过 HTTP $_POST 快速上传图片【英文标题】:Swift Image upload via HTTP $_POST 【发布时间】:2016-05-17 04:37:53 【问题描述】:我正在使用此代码 (Swift) 将用户从照片中选择的图像上传到服务器:
let imageFormatted = UIImageJPEGRepresentation(imageView.image!, 0.5);
let uuid = NSUUID().UUIDString
print ("MARK -- UUID is " + uuid)
Alamofire.upload(
.POST,
"http://www.memer.onlie/upload.php",
multipartFormData: multipartFormData in
multipartFormData.appendBodyPart(data: imageFormatted!, name: "imagefile",
fileName: uuid + ".jpg", mimeType: "image/jpeg")
,
encodingCompletion: encodingResult in
switch encodingResult
case .Success(let upload, _, _):
upload.validate()
upload.responseJSON response in
dispatch_async(dispatch_get_main_queue())
self.displayAlert("Uploaded!", message: "Your meme was uploaded, and you might see it in the app soon!", responseButtonText: "<3")
var json = JSON(data: response.data!)
print ("MARK -- JSON response: " + json["response"].stringValue)
print ("MARK -- Upload success!")
case .Failure(let encodingError):
print(encodingError)
print ("MARK -- Upload failure!")
self.displayAlert("Issue uploading.", message: "There was an issue uploading your meme.", responseButtonText: "Aww :(")
)
没有图像上传到服务器。我可以更正什么才能使其正常工作?
编辑的代码。
【问题讨论】:
【参考方案1】:此thread 可帮助您了解您未考虑的内容以及解决问题需要采取的措施。我想您需要正确设置请求标头和正文部分。如果你使用 Alamofire 并且必须使用 'multipart/form-data' 编码类型,你可以编写这样的代码。
Alamofire.upload(.POST, destURL, headers: yourHeader, multipartFormData: multipartFormData in
if let imageData = UIImageJPEGRepresentation(image, 0.5)
multipartFormData.appendBodyPart(data: imageData, name:"file", fileName: "imagefile", mimeType: "image/jpg")
// Append parameters you should send
for (key, value) in parameters
multipartFormData.appendBodyPart(data: value.dataUsingEncoding(NSUTF8StringEncoding)!, name: key)
, encodingCompletion: encodingResult in
switch encodingResult
case .Success(let upload, _, _):
upload.validate()
upload.responseJSON response in
// do something if response is success
case .Failure(_):
// do something if response is fail
)
【讨论】:
我正在使用这个,查看代码的编辑帖子,但它没有发送到服务器并且没有响应。 @woogii 您没有任何 HTTP 标头或额外参数吗?您从响应中得到的错误是什么?您可以参考此thread,其中显示了有关 Alamofire 上传请求的各种示例代码。以上是关于通过 HTTP $_POST 快速上传图片的主要内容,如果未能解决你的问题,请参考以下文章
android android-async-http 上传图片,android----AsyncHttpClient的get,post和图片上传