2015-02-11 44 views
1

進出口使用下面的代碼到一個單一的圖像上傳到服務器(帶參數),但是我一直在試圖上傳多張圖片,但不能讓它的工作多個圖像文件

創建NSData對象(保存在臨時目錄中的圖像)。使用netdata類here

func uploadData(){ 
    //create image data objects 
    let filemanager:NSFileManager = NSFileManager() 
    let files = filemanager.enumeratorAtPath(tempPicPath) 
    var counter:Int = Int() 
    while let file: AnyObject = files?.nextObject() { 
     imagePathCollection.append(tempPicPath + "/" + (file as NSString)) 
    } 

    //convert to data objects() 
    for path in imagePathCollection{ 
     var image: UIImage? = UIImage(contentsOfFile: path) 
     if image != nil { 
      var sizeOfImage = image?.size 
      var resizedImage = RBSquareImageTo(image!, sizeOfImage!) 
      var imageData = UIImageJPEGRepresentation(resizedImage, 75) 
      imageDataCollection.append(NetData(data: imageData!, mimeType:MimeType(rawValue: "image/jpeg")!, filename: "myImage.jpeg")) 
     } 
    } 

    if(imageDataCollection.count > 1){ 
     for (index, element) in enumerate(imageDataCollection) { 
      multipleImageUpload(imageDataCollection[index]) 
     } 
    }else{ 
     singleImageUpload(imageDataCollection[0]) 
    } 
} 

使用Alamofire上傳

 func extrasImageUpoload(urlRequest:(URLRequestConvertible, NSData))->Request{ 
    let request = Alamofire.upload(urlRequest.0, urlRequest.1) 
     .progress { (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in 
      println("progress : \(totalBytesWritten)/\(totalBytesExpectedToWrite)") 
    } 
    return request 
} 

生成Alamofire請求

func urlRequestWithComponents(parameters:NSDictionary, uploadType:String) -> (URLRequestConvertible, NSData) { 

    var mutableURLRequest:NSMutableURLRequest = NSMutableURLRequest() 

    //set url type 
    if(uploadType == "extra"){ 
     mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: baseURL + "ticket/extra")!) 
    }else if(uploadType == "checkList"){ 
     //uploadUrl = "ticket/mark" 
     mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: baseURL + "ticket/mark")!) 
    } 

    // create url request to send 
    //var mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: baseURL + "ticket/extra")!) 
    mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue 
    //let boundaryConstant = "myRandomBoundary12345" 
    let boundaryConstant = "NET-POST-boundary-\(arc4random())-\(arc4random())" 
    let contentType = "multipart/form-data;boundary="+boundaryConstant 
    //let pgToken = "c9049df83e8bfd7a3dfaef279cdb74478330ff2a" 
    mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type") 
    mutableURLRequest.setValue(self.token, forHTTPHeaderField: "PG-Auth-Token") 

    // create upload data to send 
    let uploadData = NSMutableData() 

    // add parameters 
    for (key, value) in parameters { 

     uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) 

     if value is NetData { 
      // add image 
      var postData = value as NetData 
      //uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(postData.filename)\"\r\n".dataUsingEncoding(NSUTF8StringEncoding)! 
      var filenameClause = " filename=\"\(postData.filename)\"" 
      let contentDispositionString = "Content-Disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n" 
      let contentDispositionData = contentDispositionString.dataUsingEncoding(NSUTF8StringEncoding) 
      uploadData.appendData(contentDispositionData!) 


      // append content type 
      //uploadData.appendData("Content-Type: image/png\r\n\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) 
      let contentTypeString = "Content-Type: \(postData.mimeType.getString())\r\n\r\n" 
      let contentTypeData = contentTypeString.dataUsingEncoding(NSUTF8StringEncoding) 
      uploadData.appendData(contentTypeData!) 
      uploadData.appendData(postData.data) 

     }else{ 
      uploadData.appendData("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n\(value)".dataUsingEncoding(NSUTF8StringEncoding)!) 
     } 
    } 
    uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) 

    // return URLRequestConvertible and NSData 
    return (Alamofire.ParameterEncoding.URL.encode(mutableURLRequest, parameters: nil).0, uploadData) 
} 

與NSData的集合沿所述參數陣列,如下

var params = ["pic":imageData,"ticketid":ticketID, "appversion":Utilities().getAPPVersion(), "description":"bla bla bla", "cost":50] 

「imageData」是圖像的NSData對象的集合。代碼工作正常,但收到的圖像的NSData數組作爲一個空的數組。然而,其他參數包括「appversion」和「description」將會收到罰款

回答

1

唯一看起來錯誤的是我沒有正確創建初始邊界。在第一個邊界開始時,你不應該有一個CRLF。我會嘗試以下代替。

let uploadData = NSMutableData() 

for (index, (key, value)) in enumerate(parameters) { 
    if index == 0 { 
     uploadData.appendData("--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) 
    } else { 
     uploadData.appendData("\r\n--\(boundaryConstant)\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) 
    } 

    if let postData as? NetData { 
     var filenameClause = " filename=\"\(postData.filename)\"" 
     let contentDispositionString = "Content-Disposition: form-data; name=\"\(key)\";\(filenameClause)\r\n" 
     let contentDispositionData = contentDispositionString.dataUsingEncoding(NSUTF8StringEncoding) 
     uploadData.appendData(contentDispositionData!) 

     let contentTypeString = "Content-Type: \(postData.mimeType.getString())\r\n\r\n" 
     let contentTypeData = contentTypeString.dataUsingEncoding(NSUTF8StringEncoding) 
     uploadData.appendData(contentTypeData!) 
     uploadData.appendData(postData.data) 
    } 
} 

uploadData.appendData("\r\n--\(boundaryConstant)--\r\n".dataUsingEncoding(NSUTF8StringEncoding)!) 
+0

感謝我給它去 – Yrol 2015-02-12 06:56:03

+0

我得到這個當我嘗試做多載「對未渲染的視圖進行快照會產生空白的快照,確保在屏幕更新後快照或快照之前,您的視圖至少已呈現一次。」 「.NetData」沒有實現methodSignatureForSelector: - 提前出現問題「 – Yrol 2015-02-12 10:42:52

+0

你的快照錯誤是一個非常不同的問題,與我提出的修改無關。我會建議提交一個不同的問題,並查看[drawViewHierarchyInRect:](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIView_Class/#//apple_ref/occ/instm/UIView/drawViewHierarchyInRect :afterScreenUpdates :)方法。至於'.NetData'問題,你還沒有發佈足夠的信息去繼續。再次,我不認爲這是我發佈的代碼的問題。 – cnoon 2015-02-12 16:15:47

1
import MobileCoreServices 


func createRequest(userid: String, image: [UIImage]) throws -> NSMutableURLRequest { 

    var parameters: [String : AnyObject] = [ 
     "userid": userid, 
     "Image1": image[0], // You need to set the UIImage Type image parameters 
     "Image2": image[1], 
     "Image3": image[2], 
     "Image4": image[3] 
    ] 

    print(parameters) 

    let boundary = generateBoundaryString() 

    let url = URL(string: Your URL String)! 
    let request = NSMutableURLRequest(url: url) 
    request.setValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type") 

    request.httpBody = try createBody(with: parameters as [String : AnyObject], boundary: boundary) 

    return request 
} 

這裏是上傳圖片的代碼和多/ form-data的參數

func createBody(with parameters: [String: AnyObject], boundary: String) throws -> Data { 

    var body = Data() 

    for (key, value) in parameters { 

     if(value is String || value is NSString) { 
      body.append("--\(boundary)\r\n") 
      body.append("Content-Disposition: form-data; name=\"\(key)\"\r\n\r\n") 
      body.append("\(value)\r\n") 
     }else if(value is UIImage) { 
      let r = arc4random() 
      let filename = "image\(r).jpg" 
      let data = UIImageJPEGRepresentation(value as! UIImage,1); 
      let mimetype = mimeTypeForPath(path: filename) 

      body.append("--\(boundary)\r\n") 
      body.append("Content-Disposition: form-data; name=\"\(key)\"; filename=\"\(filename)\"\r\n") 
      body.append("Content-Type: \(mimetype)\r\n\r\n") 
      body.append(data!) 
      body.append("\r\n") 
     } 

    } 

    body.append("--\(boundary)--\r\n") 

    return body 

} 

func mimeTypeForPath(path: String) -> String { 
    let pathExtension = path.pathExtension 
    var stringMimeType = "application/octet-stream"; 
    if let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension as! CFString, nil)?.takeRetainedValue() { 
     if let mimetype = UTTypeCopyPreferredTagWithClass(uti, kUTTagClassMIMEType)?.takeRetainedValue() { 
      stringMimeType = mimetype as NSString as String 
     } 
    } 
    return stringMimeType; 
} 

extension String { 
    var ns: NSString { 
     return self as NSString 
    } 
    var pathExtension: String? { 
     return ns.pathExtension 
    } 
    var lastPathComponent: String? { 
     return ns.lastPathComponent 
    } 
} 
相關問題