vue.jsでdrag&dropを使用したアップロード用コンポーネントを作っていきます。
環境等
| 項目 | バージョン |
|---|---|
| node | v10.15.3 |
| npm | 6.4.1 |
| vue.js | 2.6.10 |
実装
drag&dropエリア
エリアの作成
divタグで適当な大きさのボックスを作成します。
今回は、以下サイズのエリアになります。
min-width: 200pxmin-height: 200pxwidth: 100%height: 100%
イベントの設定
drop,dragoverイベントのブラウザデフォルトの処理が動かないようにすることが重要です。
デフォルトの処理が実行されると、dropしたファイルをブラウザが表示してしまうため、実行したいdrop処理が実行されません。
dragoverイベントに対しては、特にイベントを指定したいわけではなくデフォルト処理を止めたいだけなので、.prevent修飾子を利用します。
dropも同様に利用したうえで、fileを取得する処理を記載しています。
取得したファイル情報はカスタムイベントで親コンポーネントに返しています。
リスナに以下の様な関数を登録すれば、Amplify Storageを利用してS3にputすることができます。
async function upload(files) {
const file = files[0];
if (!file) return;
await this.$Amplify.Storage.put(file.name, file, {
level: "private",
contentType: file.type,
expires: Date.now() + 1000 * 60 * 60 * 24 * 1
});
}
コード
コンポーネントのコードのみとなります。
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <template> | |
| <div | |
| class="drag-area" | |
| @dragover.prevent | |
| @drop.prevent="upload" | |
| > | |
| <input type="file" @change="upload" /> | |
| <span>{{ areaMessage }}</span> | |
| </div> | |
| </template> | |
| <script> | |
| export default { | |
| name: "Upload", | |
| props: { | |
| areaMessage: { | |
| type: String, | |
| default: "Upload File" | |
| } | |
| }, | |
| methods: { | |
| upload(event) { | |
| const files = event.target.files || event.dataTransfer.files; | |
| this.$emit("upload", files); | |
| } | |
| } | |
| }; | |
| </script> | |
| <style lang="sass" scoped> | |
| .drag-area | |
| width: 100% | |
| min-width: 200px | |
| height: 100% | |
| min-height: 200px | |
| border: 1px dotted rgba(0,0,0,0.1) | |
| border-radius: 8px | |
| display: flex | |
| justify-content: center | |
| align-items: center | |
| flex-direction: column | |
| background-color: #F5F5F5 | |
| input | |
| opacity: 0 | |
| </style> |
ECMAScript,Javaを扱います。
最近は、vue.jsなどフロントエンドの技術に興味あり!
中日ドラゴンズを応援してます。


コメント