質問をすることでしか得られない、回答やアドバイスがある。

15分調べてもわからないことは、質問しよう!

新規登録して質問してみよう
ただいま回答率
85.47%
Vue.js

Vue.jsは、Webアプリケーションのインターフェースを構築するためのオープンソースJavaScriptフレームワークです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

AWS(Amazon Web Services)

Amazon Web Services (AWS)は、仮想空間を機軸とした、クラスター状のコンピュータ・ネットワーク・データベース・ストーレッジ・サポートツールをAWSというインフラから提供する商用サービスです。

Q&A

0回答

829閲覧

ブラウザから画像をアップロードすると、CORS policy のエラーが発生しアップロードできない

useretc

総合スコア11

Vue.js

Vue.jsは、Webアプリケーションのインターフェースを構築するためのオープンソースJavaScriptフレームワークです。

Python

Pythonは、コードの読みやすさが特徴的なプログラミング言語の1つです。 強い型付け、動的型付けに対応しており、後方互換性がないバージョン2系とバージョン3系が使用されています。 商用製品の開発にも無料で使用でき、OSだけでなく仮想環境にも対応。Unicodeによる文字列操作をサポートしているため、日本語処理も標準で可能です。

AWS(Amazon Web Services)

Amazon Web Services (AWS)は、仮想空間を機軸とした、クラスター状のコンピュータ・ネットワーク・データベース・ストーレッジ・サポートツールをAWSというインフラから提供する商用サービスです。

0グッド

0クリップ

投稿2019/06/29 14:57

編集2019/07/02 08:05

前提・実現したいこと

まずやってみる機械学習 ~AWS SAGEMAKER/REKOGNITIONとVUEで作る画像判定WEBアプリケーション(後編)
を参考にしながら、SAGEMAKERのテストを行いたいのですが、
「2-3. 動作確認」の「3. 実行結果を確認します」にてCORS policy のエラーが発生しアップロードできない状態です。

流れとしては、以下のイメージです。
アーキテクチャ

発生している問題・エラーメッセージ

Chromeの開発者ツールでは、下記が出力されています。

Access to XMLHttpRequest at 'https://runtime.sagemaker.us-east-1.amazonaws.com/endpoints/sagemaker-imageclassification-notebook-ep--2019-06-24-06-45-35/invocations/api/classification' from origin 'http:/xxxxxxxxxx.s3-website-us-east-1.amazonaws.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

該当のソースコード

index.html

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>ITA</title> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/siimple@3.1.0/dist/siimple.min.css"> </head> <body> <div id="app"> <div> <div class="siimple-navbar siimple-navbar--extra-large siimple-navbar--primary"> <div class="siimple-navbar-title">Image Classification Example</div> <div class="siimple-navbar-subtitle">ITA</div> </div> <div class="siimple-content siimple-content--extra-large"> <div class="siimple-grid"> <div class="siimple-grid-row"> <div class="siimple-grid-col siimple-grid-col--6 siimple-grid-col--sm-6"> <div class="siimple-h2">Select Image file</div> <input type="file" id="file" v-on:change="onFileChange"> <div class="siimple-content siimple-content--Medium"> <div v-if="image"> <img :src="image" /><br> <div class="siimple-btn siimple-btn--primary siimple-btn" v-on:click="uploadImage()">Upload</div> </div> </div> </div> <div class="siimple-grid-col siimple-grid-col--6 siimple-grid-col--sm-6"> <div class="siimple-h2">Result - SageMaker</div> <div class="siimple-list"> <div class="siimple-list-item" v-for="result in results_classification">{{ result }}</div> </div> <div class="siimple-h2">Result - Rekognition</div> <div class="siimple-list"> <div class="siimple-list-item" v-for="result in results_rekognition">{{ result }}</div> </div> </div> </div> </div> </div> </div> </div> <script src="https://unpkg.com/vue@2.5.17/dist/vue.min.js"></script> <script src="https://unpkg.com/axios@0.18.0/dist/axios.min.js"></script> <script src="./main.js"></script> </body> </html>

main.js

let app = new Vue({ el: '#app', data: { image: '', results_classification: [], results_rekognition: [], }, methods: { onFileChange: function(e) { let files = e.target.files || e.dataTransfer.files; if (!files.length) return; this.showImage(files[0]); this.results_classification = []; this.results_rekognition = []; }, showImage: function(file) { let freader = new FileReader(); freader.onload = (e) => { this.image = e.target.result; }; freader.readAsDataURL(file); }, uploadImage: function(e) { let config = { headers: { 'content-type': 'application/octet-stream', } }; axios .post( "https://<<YOUR ENDPOINT URL>>/api/classification", this.image, config ) .then(response => { this.results_classification = response.data.split(","); }) .catch(error => { console.log(error); }); axios .post( "https://<<YOUR ENDPOINT URL>>/api/rekognition", this.image, config ) .then(response => { this.results_rekognition = response.data.split(","); }) .catch(error => { console.log(error); }); } } })

APP.PY

import boto3 import base64 import json import numpy as np import logging import traceback,sys from chalice import Chalice app = Chalice(app_name='image-classification') app.debug = True logger = logging.getLogger() logger.setLevel(logging.DEBUG) @app.route('/classification', methods=['POST'], content_types=['application/octet-stream'], cors=True) def classification(): try: body_data = app.current_request.raw_body body_data = body_data.split(b'base64,') image = base64.b64decode(body_data[1]) sagemaker_client = boto3.client(service_name='sagemaker-runtime', region_name='us-east-1') logger.info('Invoke Endpoint') res = sagemaker_client.invoke_endpoint( EndpointName='<<YOUR SAGEMAKER ENDPOINT NAME>>', ContentType='application/x-image', Body = image ) result = res['Body'].read() result = json.loads(result) # the result will output the probabilities for all classes object_categories = ['ak47', 'american-flag', 'greyhound', 'tennis-shoes', 'toad', 'clutter'] out = '' index = np.argsort(result) for i in index[::-1]: out += '{} / [probability] {:.2%},'.format(object_categories[i], result[i]) if result[i] < 0.1: break return out[:-1] except Exception as e: tb = sys.exc_info()[2] return 'error:{0}'.format(e.with_traceback(tb)) @app.route('/rekognition', methods=['POST'], content_types=['application/octet-stream'], cors=True) def rekognition(): try: body_data = app.current_request.raw_body body_data = body_data.split(b'base64,') image = base64.b64decode(body_data[1]) rekognition_client = boto3.client(service_name='rekognition', region_name='us-east-1') logger.info('Invoke Rekognition') res = rekognition_client.detect_labels( Image = { 'Bytes': image }, MaxLabels=5, MinConfidence=10 ) translate_client = boto3.client(service_name='translate', region_name='us-east-1') out = '' for label in res['Labels'] : trans = translate_client.translate_text(Text=label['Name'], SourceLanguageCode='en', TargetLanguageCode='ja') out += '[en] {} / [ja] {} / [Confidence] {:.2f}%,'.format( label['Name'], trans.get('TranslatedText'), label['Confidence'] ) return out[:-1] except Exception as e: tb = sys.exc_info()[2] return 'error:{0}'.format(e.with_traceback(tb))

補足情報(FW/ツールのバージョンなど)

自分なりに調べて、Access-Control-Allow-Origin ヘッダを返すようにすればいいのは分かったのですが、実際に返すための方法がわかりませんでした。

2019/07/01追記
S3のバケットプロパティ→アクセス権限→CORS設定にてCORS構成エディタがあったため、ここに下記を設定しています。

<?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>*</AllowedHeader> <AllowedHeader>Origin</AllowedHeader> </CORSRule> </CORSConfiguration>

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

Kento75

2019/07/01 12:45

少なくともバケットのCORS設定は影響していると思います。 以下のサイトに対処法が紹介されていますので、試してみて解消されれば良いのですが。 https://hit.hateblo.jp/entry/aws/s3/CORS
useretc

2019/07/02 08:02

Kento75さん、ご回答ありがとうございます。 教えていただいた内容をもとに、S3のCORS設定を行ったのですが同じエラーが再度出ている状態です。
useretc

2019/07/03 13:27

Kento75さん、ご回答ありがとうございます。 パソコンが壊れてしまい修理に出しているため、戻り次第確認いたします。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

まだ回答がついていません

会員登録して回答してみよう

アカウントをお持ちの方は

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.47%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問