如何使用Alamofire.upload函数上传带有某些参数的图片或wav文件 [英] how to upload a picture or a wav file with some parameters using Alamofire.upload function

查看:867
本文介绍了如何使用Alamofire.upload函数上传带有某些参数的图片或wav文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将一些文件上传到服务器,但是它需要令牌才能与文件一起发布.登录时我获得了令牌,那么如何发布到服务器?我可以写这样的代码吗?

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)

推荐答案

根据您的服务器实现,当前版本的Alamofire最有可能不支持此功能.

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

您的服务器最有可能期望对数据进行multipart/form-data编码.当前,Alamofire不支持多部分表单数据.您需要根据 RFC-2388 RFC-2045 .

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.

如果最终还是这样,则可以实施自己的规范版本,也可以使用 AFNetworking .如果可以的话,我现在鼓励您使用AFNetworking.如果您确定确实要自己实现此功能,请使用线程(由@rainypixels提供)开始.

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.

文件上传

如果服务器不希望使用multipart/form-data编码,则可以使用Alamofire上传方法.

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

您可以创建一个NSURLRequest,并将令牌添加为参数,然后将fileURL传递给Alamofire进行上传.

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.

这篇关于如何使用Alamofire.upload函数上传带有某些参数的图片或wav文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆