how to upload a picture or a wav file with some parameters using Alamofire.upload function

倾然丶 夕夏残阳落幕 提交于 2019-12-12 03:14:39

问题


I want to upload some file to a server, but it needs a token to post with the file together. I got the token when I logged in, so how could I post to the server? Can I write code like this?

var par=[
           "token":"xxxxxxxxxx",
           "file":"filename.file"
]
Alamofire.upload(.POST, "http://www.xxxxx.xxx", parameters: par)

回答1:


This is most likely not supported in the current version of Alamofire depending on your server implementation.

Multipart Form Data

Your server most likely expects the data to be multipart/form-data encoded. Currently, multipart form data is not supported by Alamofire. You will need to encode the data yourself according to the RFC-2388 and RFC-2045.

If this ends up being the case, you can either implement your own version of the specs, or you could use AFNetworking. I would encourage you at the moment to use AFNetworking if this is the case. Here is a thread (courtesy of @rainypixels) to get you started if you decide you really want to implement this yourself.

You need to be careful with this option as it is an in-memory solution. Do NOT attempt to upload videos or large numbers of images in this way or your app out-of-memory very quickly.

File Upload

If the server does not expect multipart/form-data encoding, then you can use the Alamofire upload method.

public func upload(URLRequest: URLRequestConvertible, file: NSURL) -> Request

You could create an NSURLRequest with the token appended as a parameter, then pass the fileURL off to Alamofire to be uploaded.

In summary, I'm pretty certain that the first approach is what your server is going to require. Either way, hopefully this helps you get heading in the right direction.



来源:https://stackoverflow.com/questions/29224596/how-to-upload-a-picture-or-a-wav-file-with-some-parameters-using-alamofire-uploa

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!