Browse Source

Add `customFetch` option in AssetManager module

pull/1775/head
Artur Arseniev 7 years ago
parent
commit
c9ff4eda21
  1. 12
      src/asset_manager/config/config.js
  2. 16
      src/asset_manager/view/FileUploader.js

12
src/asset_manager/config/config.js

@ -55,7 +55,17 @@ module.exports = {
// Label for the add button // Label for the add button
addBtnText: 'Add image', addBtnText: 'Add image',
// Custom uploadFile function // To upload your assets, the module uses Fetch API, with this option you
// overwrite it with something else.
// It should return a Promise
// @example
// customFetch: (url, options) => axios(url, { data: options.body }),
customFetch: '',
// Custom uploadFile function.
// Differently from the `customFetch` option, this gives a total control
// over the uploading process, but you also have to emit all `asset:upload:*` events
// by yourself (if you need to use them somewhere)
// @example // @example
// uploadFile: (e) => { // uploadFile: (e) => {
// var files = e.dataTransfer ? e.dataTransfer.files : e.target.files; // var files = e.dataTransfer ? e.dataTransfer.files : e.target.files;

16
src/asset_manager/view/FileUploader.js

@ -104,9 +104,9 @@ module.exports = Backbone.View.extend(
* */ * */
uploadFile(e, clb) { uploadFile(e, clb) {
const files = e.dataTransfer ? e.dataTransfer.files : e.target.files; const files = e.dataTransfer ? e.dataTransfer.files : e.target.files;
const { config } = this;
const body = new FormData(); const body = new FormData();
const config = this.config; const { params, customFetch } = config;
const params = config.params;
for (let param in params) { for (let param in params) {
body.append(param, params[param]); body.append(param, params[param]);
@ -131,18 +131,20 @@ module.exports = Backbone.View.extend(
if (url) { if (url) {
this.onUploadStart(); this.onUploadStart();
return fetch(url, { const fetchOpts = {
method: 'post', method: 'post',
credentials: config.credentials || 'include', credentials: config.credentials || 'include',
headers, headers,
body body
}) };
.then( const fetchResult = customFetch
res => ? customFetch(url, fetchOpts)
: fetch(url, fetchOpts).then(res =>
((res.status / 200) | 0) == 1 ((res.status / 200) | 0) == 1
? res.text() ? res.text()
: res.text().then(text => Promise.reject(text)) : res.text().then(text => Promise.reject(text))
) );
return fetchResult
.then(text => this.onUploadResponse(text, clb)) .then(text => this.onUploadResponse(text, clb))
.catch(err => this.onUploadError(err)); .catch(err => this.onUploadError(err));
} }

Loading…
Cancel
Save