好的,我正在使用Mapbox的Javascript uploads API来允许用户直接从浏览器将文件上传到我的Mapbox帐户。
我已成功使用JS从浏览器将文件上传到Mapbox帐户。但是,有一个问题。
如果我使用 Localhost 服务器上传,一切正常,文件上传到AWS S3存储桶,最后上传到Mapbox。但是,如果我从某些非localhost域运行相同的代码(例如:www.mydomain.co),我会收到 createUploadCredentials()方法的CORS错误,该方法会停止进一步的JS执行。所以问题是,为什么createUploadCredentials()只允许本地主机而不允许任何其他域?
在下面的屏幕截图中,您可以看到我在Localhost中获取CORS头,但在非localhost域中没有。因为没有CORS头我在生产中得到了CORS错误: Localhost与非localhost域http请求 - 响应:
然而,即使存在CORS错误,我也会获得Mapbox凭据响应:
这是我的Angular2-Typescript代码:
文件上传器事件
fileChange(event) {
let fileList: FileList = event.target.files;
if (fileList.length > 0) {
let file: File = fileList[0];
this._importDataService.getMapboxUploadInitData().then((uploadInitData: IMapBoxUploadInitData) => {
this.uploadFile(file, uploadInitData);
this.uploadInProgress = true;
}, (err: any) => {
this.uploadInProgress = false;
})
}
}
上传文件:
uploadFile(file: File, uploadInitData: IMapBoxUploadInitData) {
let fileName = file.name.substring(0, file.name.lastIndexOf('.'));
let tilesetName = [uploadInitData.mapboxUserName, fileName].join('.') + uploadInitData.tilesetNameAppend;
if (tilesetName.length > uploadInitData.maxTilesetNameLengthAllowed) {
alert('File name should be less than or equal to' + uploadInitData.maxTilesetNameLengthAllowed + ' characters long');
return false;
}
this.client = new MapboxClient(uploadInitData.temporaryMapboxToken);
//Here I get the CORS error and further execution stops:
this.client.createUploadCredentials((err, credentials) => {
if (err) {
this.uploadInProgress = false;
console.log(err);
return
}
// Use aws-sdk to stage the file on Amazon S3
let bucket = new AWS.S3({
accessKeyId: credentials.accessKeyId,
secretAccessKey: credentials.secretAccessKey,
sessionToken: credentials.sessionToken,
region: 'us-east-1'
});
var putObj = {
Bucket: credentials.bucket,
Key: credentials.key,
Body: file,
ContentType: file.type
}
bucket.upload(putObj).on('httpUploadProgress', (evt: any) => {
// Watch the AWS bucket upload progress
this.uploadProgressValue = Math.floor((evt.loaded * 100) / evt.total);
this.uploadProgressPercent = this.uploadProgressValue + '%';
}).send((err, data) => {
this.uploadInProgress = false;
this.client.createUpload({
tileset: tilesetName,
url: credentials.url,
name: fileName
}, (err, mapboxUpload) => {
this.uploadInProgress = false;
if (err) {
console.log(err);
return
}
this.upload = mapboxUpload
// Check every 5 seconds until the upload is complete
this.uploadInterval = setInterval(() => this.checkUpload(), 5000);
});
});
});
}
检查Mapbox处理进度:
checkUpload() {
// Check to see if an unload is complete
this.client.readUpload(this.upload.id, (err, myupload) => {
if (err) {
window.alert(err);
return
}
console.log('myupload', myupload);
if (myupload.complete === true) {
clearInterval(this.uploadInterval);
this.upload = myupload
}
})
};