问题非常简单:
我需要将.zip文件上传到服务器,如何使用Siesta Framework在Swift中执行此操作?
谢谢。
答案 0 :(得分:2)
实际上,以上答案并不完全正确。 由于Siesta长期以来都支持POST请求,因此您可以按照以下方式(例如PNG或JPEG文件上传)在YourAPI类中上传文件(内容类型:multipart / form-data):
Enter/Leave
要使用它(从您的ViewController):
class YourAPI {
static let sharedInstance = YourAPI()
private let service = Service(baseURL: "http://your_server/rest/service", standardTransformers: [.text, .image])
private init() {
// your init code
}
public enum ImageType {
case png
case jpeg
}
func generateBoundaryString() -> String {
return "Boundary-\(UUID().uuidString)"
}
func constructHttpBodyForImageUpload(withBoundary boundary: String, imageData: Data, fileName: String, imageType: ImageType) -> Data {
let body = NSMutableData()
var mimetype = "image/png" // default
if imageType == .jpeg {
mimetype = "image/jpeg"
}
body.append("--\(boundary)\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Disposition:form-data; name=\"file\"; filename=\"\(fileName)\"\r\n".data(using: String.Encoding.utf8)!)
body.append("Content-Type: \(mimetype)\r\n\r\n".data(using: String.Encoding.utf8)!)
body.append(imageData)
body.append("\r\n".data(using: String.Encoding.utf8)!)
body.append("--\(boundary)--\r\n".data(using: String.Encoding.utf8)!)
return body as Data
}
@discardableResult func uploadImage(_ imageData: Data, fileName: String, imageType: ImageType, onSuccess: @escaping () -> Void, onFailure: @escaping (String) -> Void) -> Request {
let boundary = generateBoundaryString()
let request = service.resource("/files/upload").request(.post) {
// See comments in Siesta Resource.swift class for .post
$0.httpBody = self.constructHttpBodyForImageUpload(withBoundary: boundary, imageData: imageData, fileName: fileName, imageType: imageType)
$0.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
}
// My Server returns me JSON back
request.onSuccess { entity in
guard let json: [String: String] = entity.typedContent() else {
onFailure("JSON parsing error")
return
}
guard let status = json["status"] else {
onFailure("Responce status is missing")
return
}
print("status = \(status)")
}.onFailure { (error) in
onFailure(error.userMessage)
}
return request
}
} // YourAPI
另外几天以来,Siesta项目guthub提出了一个拉取请求,以实现:Convenience method for multipart/form-data requests,这可以很快成为框架的标准部分,并可以减少上述样板代码的大小。
答案 1 :(得分:1)
根据the GitHub page of Siesta,目前不支持文件上传/下载任务。请参阅此比较图表: