精华内容
下载资源
问答
  • swift上传图片

    2017-02-15 17:34:00
    import UIKit import AFNetworking class YJRequest: NSObject { ... //#pragma mark - 上传图片 func uploadImageWithImage(_ imageData: Data){ let sessionConfiguration = URLSessionConf...
    import UIKit
    import AFNetworking
    
    class YJRequest: NSObject {
        
        //#pragma mark - 上传图片 
        func uploadImageWithImage(_ imageData: Data){
    
        let sessionConfiguration = URLSessionConfiguration.default
        let manager =  AFHTTPSessionManager(sessionConfiguration: sessionConfiguration)
        manager.responseSerializer.acceptableContentTypes = NSSet(arrayLiteral: "application/json", "text/json", "text/javascript","text/html") as? Set<String>
    
            manager.post("", parameters: ["":""], constructingBodyWith: { (formData) in
                let formatter = DateFormatter()
                formatter.dateFormat = "yyyyMMddHHmmss"
                formatter.timeZone = NSTimeZone.system
                let fileName:String = "\(formatter.string(from: NSDate.init() as Date)).jpg"
                formData.appendPart(withFileData: imageData, name: "head", fileName: fileName, mimeType: "image/png")
                }, progress: { (progress) in
                    //
                }, success: { (task, response) in
                    //
                    print("suceess")
                }) { (task, error) in
                    //
                     print(error)
            }
            
        }
    }

     

    举了个最简单的例子,没有任何封装与扩展,仅仅供参考

     

    转载于:https://www.cnblogs.com/yajunLi/p/6393882.html

    展开全文
  • swift开发一个小项目,但是要上传图片到服务器,服务器现在想用java实现,就简单的接收图片并保存,同时返回给app一个网址,试了好久还是没能成功实现,求大神指点,有代码就最好了,谢谢!
  • let docDir:AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] let imagePath = docDir + "/myPic.jpg" var imageData = NSData(contentsOfFile: imagePat...
    
     
    let docDir:AnyObject = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] 
    
    let imagePath = docDir + "/myPic.jpg"
    
     var imageData = NSData(contentsOfFile: imagePath, options:NSDataReadingOptions.DataReadingMappedIfSafe, error: nil)
    
     var parameters = [ "pic" :NetData(nsData: imageData!, filename: "customName.jpg"), "otherParm" :"Value" ]
    
     let urlRequest = self.urlRequestWithComponents("http://www.example.com/upload.php", parameters: parameters)

     

    
     

     

    Alamofire.upload(urlRequest.0, urlRequest.1) .progress { 
    (bytesWritten, totalBytesWritten, totalBytesExpectedToWrite) in println("\
    
    (totalBytesWritten) / \(totalBytesExpectedToWrite)") 
    }
    
     } 

     

    
    
    func urlRequestWithComponents(urlString:String, parameters:NSDictionary) -> (URLRequestConvertible, NSData) {
    
        // create url request to send
        var mutableURLRequest = NSMutableURLRequest(URL: NSURL(string: urlString)!)
        mutableURLRequest.HTTPMethod = Alamofire.Method.POST.rawValue
        //let boundaryConstant = "myRandomBoundary12345"
        let boundaryConstant = "NET-POST-boundary-\(arc4random())-\(arc4random())"
        let contentType = "multipart/form-data;boundary="+boundaryConstant
        mutableURLRequest.setValue(contentType, forHTTPHeaderField: "Content-Type")
    
    
        // 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)!)
    
                // append content disposition
                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)!) // mark this. 
                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)
    }
    展开全文
  • OSS图片上传 swift

    2018-08-07 09:50:48
    1.Other.swift中配置相应的参数和图片保存路径 2. OSSUploadManager().uploadImage(image:UIImage,type:EnumPicType,success:@escaping OSSUploadBlock)上传单张图片 3.OSSUploadManager().uploadImagesArr(imageArr...
  • swift 原生文件图片上传,内含原生网络请求,swift 原生文件图片上传,内含原生网络请求
  • 大神可否问个问题,我用swift实现本地生成token,基于mac最终本来应当的encoded_signed之后的字符串是28位,我用oc的sdk方法生成的是57位,求大神有空帮我看看错在哪里啊:func generateToken(accessKey: NSString!...

    大神可否问个问题,我用swift实现本地生成token,基于mac最终本来应当的encoded_signed之后的字符串是28位,我用oc的sdk方法生成的是57位,求大神有空帮我看看错在哪里啊:

    func generateToken(accessKey: NSString!, secretKey: NSString!, bucketName: NSString!) -> String{

    // 确定上传策略

    // 第二步:

    // 将上传策略序列化成为json格式:

    // {"scope":"test-scope","deadline":1477997128}

    // 第三步:

    // 对json序列化后的上传策略进行URL安全的Base64编码,得到如下encoded:

    // eyJzY29wZSI6InRlc3Qtc2NvcGUiLCJkZWFkbGluZSI6MTQ3Nzk5NzEyOH0=

    // 第四步:

    // 用SecretKey对编码后的上传策略进行HMAC-SHA1加密,并且做URL安全的Base64编码,得到如下的encoded_signed:

    // lHglRYz+TLhmFxb6LkI2ekXn0Cc=

    // 第五步:

    // 将 AccessKey、encode_signed 和 encoded 用 “:” 连接起来,得到如下的UploadToken:

    // 33HnfbHNaNgwZbIsuEO3gkXmhEZtUzDhFfHaK2YK:lHglRYz-TLhmFxb6LkI2ekXn0Cc=:eyJzY29wZSI6InRlc3Qtc2NvcGUiLCJkZWFkbGluZSI6MTQ3Nzk5NzEyOH0=

    let deadline = NSDate().timeIntervalSince1970

    print(deadline)

    print(Int(deadline))

    let policyDict: Dictionary = ["scope": bucketName, "deadline": Int(deadline) + 3600]

    let policyJSONData = try! JSONSerialization.data(withJSONObject: policyDict, options: .prettyPrinted)

    let policyJSON = NSString(data: policyJSONData, encoding: String.Encoding.utf8.rawValue)

    print(policyJSON)

    let policyData = policyJSON?.data(using: String.Encoding.utf8.rawValue)

    let encodedPolicy = QN_GTM_Base64.string(byWebSafeEncoding: policyData, padded: true)

    print(encodedPolicy)

    let hmacStr = encodedPolicy?.hmac(algorithm: .SHA1, key: secretKey as String)

    let hmacData = hmacStr?.data(using: .utf8)

    let encodedSigned = QN_GTM_Base64.string(byWebSafeEncoding: hmacData, padded: true)

    print(encodedSigned)

    let token = "\(accessKey!):\(encodedSigned!):\(encodedPolicy!)"

    return token

    }

    展开全文
  • IOS Swift 选择图片或拍照上传 UIImagePickerController声明大致介绍提供委托对象调整闪光模式处理视频资源我常用的代码模块 UIImagePickerController A view controller that manages the system interfaces for ...

    UIImagePickerController

    A view controller that manages the system interfaces for taking pictures, recording movies, and choosing items from the user’s media library.
    UIImagePickerController是一个用于拍照、摄像以及从用户媒体库上传图片或视频的管理器。

    声明

    class UIImagePickerController : UINavigationController
    

    大致介绍

    An image picker controller manages user interactions and delivers the results of those interactions to a delegate object. The role and appearance of an image picker controller depend on the source type you assign to it before you present it.
    UIImagePickerControlle让用户可以选择图片或视频,并将选择好的对象传递给委托对象上,具体上传哪种多媒体资源并且以何种方式(从媒体库选择还是拍照上传)取决于你规定的source type这个参数。

    • UIImagePickerController.SourceType.camera,拍照或录像上传
    • UIImagePickerController.SourceType.photoLibrary或UIImagePickerController.SourceType.savedPhotosAlbum,从已保存的图片或视频中选择上传

    ps:这些都需要你在Info.plist中设置申请权限,否则不能正常使用:
    在这里插入图片描述

    To use an image picker controller containing its default controls, perform these steps:
    要正常使用UIImagePickerControlle,需要做以下几步:

    1. Verify that the device is capable of picking content from the desired source. Do this by calling the isSourceTypeAvailable(_ : ) class method, providing a constant from the UIImagePickerController.SourceType enumeration.
      使用isSourceTypeAvailable方法,sourcetype作为其参数,以此判断设备是否可以获取到指定的资源类型。
    if UIImagePickerController.isSourceTypeAvailable(.camera) {
    ...
    }
    
    1. Check which media types are available for the source type you’re using, by calling the availableMediaTypes(for:) class method. This lets you distinguish between a camera that can be used for video recording and one that can be used only for still images.
      通过使用availableMediaTypes(for:)方法,你可以知道在你指定的sourcetype中你可以获取哪种文件格式,比如相机,就需要区分是录像用的还是拍摄静态图片用的。
    2. Tell the image picker controller to adjust the UI according to the media types you want to make available—still images, movies, or both—by setting the mediaTypes property.
      通过设置mediaTypes参数,你可以选择你需要的文件格式,是静态图片,还是视频,还是都可以。
    3. Present the user interface. On iPhone or iPod touch, do this modally (full-screen) by calling the present( :animated:completion:) method of the currently active view controller, passing your configured image picker controller as the new view controller.
      下面需要显示交互页面,在当前view controller下使用present(_:animated:completion:) 方法,将image picker controller作为一个新的view controller显示出来。
    4. When the user taps a button to pick a newly-captured or saved image or movie, or cancels the operation, dismiss the image picker using your delegate object. For newly-captured media, your delegate can then save it to the Camera Roll on the device. For previously-saved media, your delegate can then use the image data according to the purpose of your app.
      当用户选择好了图像或视频资源,或是点击取消按钮,你需要让image picker消失,回到之前的页面。如若选择好了资源,在回到之前页面后,委托对象应该保存好资源。

    提供委托对象

    要使用image picker controller你必须提供一个符合UIImagePickerControllerDelegate协议的委托。从iOS 4.1开始,你可以使用委托将静态图像元数据保存到相机中。

    调整闪光模式

    从iOS 4.0开始,你可以让有闪光灯设备的用户调整闪光模式,选择前置或后置摄像头,选择拍照和录像功能。你还可以通过程序管理这些设置,比如调整闪光灯模式:
    UIImagePickerController.CameraFlashMode.on 开启闪光灯
    UIImagePickerController.CameraFlashMode.off 关闭闪光灯

    处理视频资源

    视频资源默认最长不超过10分钟,但是你也可以通过设置videoMaximumDuration参数来调整视频的最长时长。
    默认的相机界面支持编辑以前保存的电影,编辑包括剪裁并保存,要显示专门用于视频编辑的界面,而不是同时支持录制新视频的界面,你可以使用UIVideoEditorController。

    我常用的代码模块

    public var imagePickerController: UIImagePickerController?
    
    @IBOutlet weak var imageView: UIImageView!
    
    //storyboard界面有UIImageView,如果未上传新的图片,则显示默认图片,如果上传,显示新上传的图片
    internal var selectedImage: UIImage? {
            get {
                return self.imageView.image
            }
            
            set {
                switch newValue {
                case nil:
                    self.imageView.image = nil
                default:
                    self.imageView.image = newValue
                }
            }
        }
    
    @IBAction func uploadImage(_ sender: UIButton) {
            /// present image picker
            
            if self.imagePickerController != nil {
                self.imagePickerController?.delegate = nil
                self.imagePickerController = nil
            }
            
            self.imagePickerController = UIImagePickerController.init()
            
            let alert = UIAlertController.init(title: "Select Source Type", message: nil, preferredStyle: .actionSheet)
            
            //拍照上传
            if UIImagePickerController.isSourceTypeAvailable(.camera) {
                alert.addAction(UIAlertAction.init(title: "Camera", style: .default, handler: { (_) in
                    self.presentImagePicker(controller: self.imagePickerController!, source: .camera)
                }))
            }
            
            //从媒体库上传
            if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
                alert.addAction(UIAlertAction.init(title: "Photo Library", style: .default, handler: { (_) in
                    self.presentImagePicker(controller: self.imagePickerController!, source: .photoLibrary)
                }))
            }
            
            //取消上传
            alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel))
            
            self.present(alert, animated: true)
        }
    
    internal func presentImagePicker(controller: UIImagePickerController , source: UIImagePickerController.SourceType) {
            controller.delegate = self
            controller.sourceType = source
            controller.allowsEditing = true //可编辑
            self.present(controller, animated: true)
        }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
            
            guard let type = info[UIImagePickerController.InfoKey.mediaType] as? String else {
                return self.imagePickerControllerDidCancel(picker)
            }
            
            //显示编辑后的图片
            guard let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage else {
                return self.imagePickerControllerDidCancel(picker)
                }
                
            self.selectedImage = image
             
            //取消上传
            picker.dismiss(animated: true) {
                picker.delegate = nil
                self.imagePickerController = nil
            }
            
        }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
            picker.dismiss(animated: true) {
                picker.delegate = nil
                self.imagePickerController = nil
            }
        }
    
    
    
    
    展开全文
  • swift利用Alamofire上传图片

    千次阅读 2016-07-12 23:11:50
    接口名称 上传头像 接口地址 /data/upload 传入参数 MultipartFile file, String phoneId, Integer phoneType 传出结果 //0 ok, 1 空文件, 2 文件写失败 分析: 接口需要传三个参数,file为图片的二进制...
  • // 新的图片 let cgimg: CGImage = ctx.makeImage()! let img: UIImage = UIImage(cgImage: cgimg) return img } }   转载于:https://my.oschina.net/zhaodacai/blog/789308
  • 之前一直用的oc图片上传!由于新项目的需要使用了swift语言,... post请求上传图片 - parameter urlString: 请求的url - parameter parameters: 请求的参数 - parameter success: 请求成功回调 - parameter failu
  • 服务器人员说图片最大只能为1M,图片质量要求尽量清晰,不得裁剪 先调整分辨率,再调整图片质量系数 “` class func reSizeImageData(sourceImage : UIImage, maxImageSize : CGFloat , maxSize : CGFloat) -> ...
  • swift post get上传图片和snapKit的简易使用
  • 想作为移动端的后台使用,奈何一直被一个问题困扰,上传字符串很轻松的就实现了,但是上传文件或者图片总是失败,困扰了日之后终于解决了,原来一直以来方向都搞错了,一直认为是 django 的代码问题,后来才发现是 swift ...
  • 创建网络上传任务 let task = session.uploadTaskWithRequest(request, fromData: body) { ( da:NSData?, co:NSURLResponse?, e:NSError?) -> Void in } task.resume() /** 压缩图片的方法, :param: ...
  • 下面使用Alamofire上传图片到服务器 参考: http://www.jianshu.com/p/cdbad52fd340 http://www.cocoachina.com/bbs/read.php?tid=317460 http://blog.csdn.net/aa31140105/article/details/51893318
  • 使用Swift的URLRequest同时上传图片和其他参数 有时候我们会有同时上传图片和其他参数(比如图片来源、名称等)的需求,这个时候一搬都会使用multipart/formdata形式上传,第三方库用多了,那如何用Swift原生代码...
  • 前言:基于Alamofire4.5网络框架开发的Swift项目中上传文件和图片代码参考。 上传文件 extension HttpRequestService { typealias UploadDoneBlock = (_ dict:[String : Any]) -> Void//成功block func ...
  • Alamofire.upload(.POST, url, multipartFormData: { (data1 : MultipartFormData) -> Void in for var i = 0 ; i ; i++ { let data = UIImageJPEGRepresentati
  • swift3.0 队列请求, 以上传图片为例
  • 在使用Alamofire这个swift的第三方http请求长传时,一般都是上传一些基本的String等类型的数据,但是在大多数的app中往往需要上传一些例如图片等等的文件,同时需要获取它的success请求成功后的返回值,在这里来给...
  • 不断的上传图片麻烦吗?快试试这个!放在 Mac 状态栏,直接拖拽就能自动上传。
  • 以下是swift 上传4张图片到服务器上,服务器只能成功收到第一张。服务器后台采用的是Request.files来处理的。Request.files[ 0]是有数据,Request.files[1]等没有数据。  请大虾帮帮看看以下代码(swift + ...
  • Sumo 是一个快速图片上传iOS库(多图片自动压缩上传

空空如也

空空如也

1 2 3 4 5 ... 11
收藏数 201
精华内容 80
关键字:

swift上传图片