Add CSP file uploads

This commit is contained in:
richard-dds
2019-07-30 16:51:58 -04:00
parent e333f32aea
commit 8eba9a097d
11 changed files with 390 additions and 34 deletions

View File

@@ -6,6 +6,8 @@ import FormMixin from '../mixins/form'
import textinput from './text_input'
import optionsinput from './options_input'
import { buildUploader } from '../lib/upload'
export default {
name: 'uploadinput',
@@ -18,6 +20,12 @@ export default {
props: {
name: String,
token: {
type: Object,
},
objectName: {
type: String,
},
initialData: {
type: String,
},
@@ -44,6 +52,7 @@ export default {
},
created: function() {
this.uploader = buildUploader(this.token)
emitEvent('field-mount', this, {
optional: this.optional,
name: this.name,
@@ -52,9 +61,17 @@ export default {
},
methods: {
addAttachment: function(e) {
this.attachment = e.target.value
this.showErrors = false
addAttachment: async function(e) {
const file = e.target.files[0]
try {
await this.uploader.upload(file, this.objectName)
this.attachment = e.target.value
this.showErrors = false
} catch (err) {
console.log(err)
this.showErrors = true
}
this.changed = true
emitEvent('field-change', this, {

64
js/lib/upload.js Normal file
View File

@@ -0,0 +1,64 @@
import Azure from 'azure-storage'
class AzureUploader {
constructor(sasToken) {
this.sasToken = sasToken.token
}
async upload(file, objectName) {
const blobService = Azure.createBlobServiceWithSas(
'https://atat.blob.core.windows.net',
this.sasToken
)
const fileReader = new FileReader()
const options = {
contentSettings: {
contentType: 'application/pdf',
},
metadata: {
filename: file.name,
},
}
return new Promise((resolve, reject) => {
fileReader.addEventListener('load', function(f) {
blobService.createBlockBlobFromText(
'task-order-pdfs',
`${objectName}.pdf`,
f.target.result,
options,
function(err, result) {
if (err) {
reject(err)
} else {
resolve(result)
}
}
)
})
fileReader.readAsText(file)
})
}
}
class AwsUploader {
constructor(presignedPost) {
this.presignedPost = presignedPost
}
async upload(file, objectName) {
const form = new FormData()
Object.entries(this.presignedPost.fields).forEach(([k, v]) => {
form.append(k, v)
})
form.append('file', file)
form.set('x-amz-meta-filename', file.name)
return fetch(this.presignedPost.url, {
method: 'POST',
body: form,
})
}
}
export const buildUploader = token => new AzureUploader(token)