Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
3
Help us understand the problem. What is going on with this article?
@hamazi511

SwiftからLambdaを経由してs3に画像をアップロードする

More than 1 year has passed since last update.

やりたいこと

SwiftからAPIGatewayとLambdaを経由してs3に画像をアップロードします。
あまり大したことはやっていませんが、細かいところで詰まったので、まとめておきます。

フロントエンド(Swift)

imageUpload.swift
 func uploadImage(image: UIImage) { 
     //画像のリサイズ
     let height = image.size.height 
     let width = image.size.width 
     let reSize  = CGSize(width: 200, height: 200*height/width) 
     let resizedImage = image.reSizeImage(reSize: reSize) 

     if let data = resizedImage.jpegData(compressionQuality: 1.0) { 
         let encodedString = data.base64EncodedString()        
         let endURL = "APIGateWayで作成したURLを入力" 
         var parameters = [String: String]() 
         parameters["body"] = encodedString 

         let apimanager = APIManager(url: endURL, method: .post, parameters: parameters, view: nil) |
         apimanager.request(fail: { () in 
             print ("成功")
         }, success: { (json: JSON) in 
             print ("失敗")      
         })     
     } 
 } 
APIManager.swift
import Foundation
import Alamofire
import SwiftyJSON

struct APIManager {

    let url: String
    let method: HTTPMethod
    let parameters: Parameters?

    init(url: String, method: HTTPMethod, parameters: Parameters?, view: UIViewController?) {
        self.url = url
        self.method = method
        self.parameters = parameters
    }

    func request(fail: @escaping () -> Void, success: @escaping (_ data: JSON) -> Void) {

        Alamofire.request(self.url, method: self.method, parameters: self.parameters, encoding: JSONEncoding.default, headers: headers).responseJSON { response in

            if (response.error != nil) {
                fail()
                return
            }
            guard let object = response.result.value else {
                fail()
                return
            }
            let json = JSON(object)
            if let _ = json["errorMessage"].string {
                fail()
                return
            }
            success(json)
        }
 }

サーバーサイド(Node.js)

imageUpload.js
const aws = require('aws-sdk')
const s3 = new aws.S3()

exports.handler = (event, context, callback) => {

  const fileData = event.body.replace(/^data:\w+\/\w+;base64,/, '')
  let requestBody = Buffer.from(fileData, 'base64')

  s3.putObject({
    Body: requestBody,
    Bucket: 'バケット名', 
    ContentType: 'image/jpeg',
    Key: 'image/hoge'
  }).promise()

    .then((result) => {
      let resp = {
                statusCode: 200,
                body: result,
                headers: {},
                isBase64Encoded: false
      }; 

      callback(null, resp)
    })
    .catch((err) => {
        callback(err)
    })
}

アップロードした画像の取得について

画像の取得にもずっとLambdaを使って取得しており、画像表示の遅さに悩んでいました。画像の取得に関してはRoute53でドメインとs3を繋げて、Lambdaを使わずに行うのが速いです。

3
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
hamazi511
都内で大学生をしながら、dancyのCTOを務めています。得意言語はSwiftです。

Comments

No comments
Sign up for free and join this conversation.
Sign Up
If you already have a Qiita account Login
3
Help us understand the problem. What is going on with this article?