Help us understand the problem. What is going on with this article?

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

やりたいこと

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を使わずに行うのが速いです。

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
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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