ant pro 使用upload上傳文件

目前公司中有寫到導入文件的功能模塊, 目前使用的技術棧是react 但是在前家公司使用的請求是用 axios 然後自己封裝一個post get請求這種, 本次是直接使用ant-pro的盒子, 所以使用的是dva , 請求方式是通過dispatch來發起的, 那麼該怎麼發起請求和傳遞參數
一開始也使用了form表單來提交上傳文件 但是碰到各種問題, 比如請求以後會跳轉頁面 , 使用iframe禁止跳轉頁面以後 他又不發起請求了 等等一系列問題.

上傳功能:

  1. 點擊上傳文件
    在這裏插入圖片描述
    在這裏插入圖片描述

<Upload {...props}>
 <Button type="primary">
   上傳文件
 </Button>
</Upload>
  1. 選擇文件
    在這裏插入圖片描述

  2. 選擇文件以後 並沒有直接上傳 , 可以自己手動點擊上傳按鈕再上傳
    在這裏插入圖片描述

const props = {
     onRemove: file => {
       this.setState(state => {
         const index = state.fileList.indexOf(file);
         const newFileList = state.fileList.slice();
         newFileList.splice(index, 1);
         return {
           fileList: newFileList,
         };
       });
     },
     beforeUpload: file => {
       this.setState(state => ({
         fileList: [...state.fileList, file],
       }));

       return false;
     },
     fileList,
   };
  1. 點擊提交, 提交文件和需要傳到 後臺的參數
    在這裏插入圖片描述
  // 提交上傳文件
  onSubmitUpload = () => {
    const { fileList } = this.state;
    const importFile = new FormData();
    fileList.forEach(file => {
      importFile.append('file', file);
      importFile.append('name', this.state.nameValue);
      importFile.append('version', this.state.versionValue);
      importFile.append('userId', this.state.userIdValue);
    });
  
    this.setState({
      uploading: true,
    });
    const { dispatch } = this.props;
    dispatch({
      type: 'list/upload',
      payload: importFile,
      callback: (response) => {
        console.log(response)   
      }
    });
  };
  • 4.1 請求的部分
  • 在這裏插入圖片描述
import { uploadList } from '@/services/api';

export default {
  namespace: 'list',

  state = {
    data: []
  },
  effects: {
    
    *upload ({ payload, callback }, { call, put }) {
      const response = yield call(uploadList, payload);
      yield put({
        type: 'save',
        payload: response
      });
      if (callback) callback(response);

    },
  },

  reducers: {
    save (state, { payload }) {
      return {
        ...state,
        data: [...payload]
      };
    },
  },
};
  • 4.2 api.js中
    在這裏插入圖片描述
import request from '@/utils/request';
// 導入
export async function uploadList (params) {
  return request('/api/download', {
    method: 'POST',
    body: params,
  });
}
  • 4.3 request.js中
    -request.js裏面的東西基本沒變, 當你下載下來ant-pro的時候 他就已經是封裝好的了
import fetch from 'dva/fetch';
import { notification } from 'antd';
import router from 'umi/router';
import hash from 'hash.js';
import { isAntdPro } from './utils';

const codeMessage = {
  200: '服務器成功返回請求的數據。',
  201: '新建或修改數據成功。',
  202: '一個請求已經進入後臺排隊(異步任務)。',
  204: '刪除數據成功。',
  400: '發出的請求有錯誤,服務器沒有進行新建或修改數據的操作。',
  401: '用戶沒有權限(令牌、用戶名、密碼錯誤)。',
  403: '用戶得到授權,但是訪問是被禁止的。',
  404: '發出的請求針對的是不存在的記錄,服務器沒有進行操作。',
  406: '請求的格式不可得。',
  410: '請求的資源被永久刪除,且不會再得到的。',
  422: '當創建一個對象時,發生一個驗證錯誤。',
  500: '服務器發生錯誤,請檢查服務器。',
  502: '網關錯誤。',
  503: '服務不可用,服務器暫時過載或維護。',
  504: '網關超時。',
};

const checkStatus = (response) => {
  if (response.status >= 200 && response.status < 300) {
    return response;
  }
  const errortext = codeMessage[response.status] || response.statusText;
  notification.error({
    message: `請求錯誤 ${response.status}: ${response.url}`,
    description: errortext,
  });
  const error = new Error(errortext);
  error.name = response.status;
  error.response = response;
  throw error;
};

const cachedSave = (response, hashcode) => {
  /**
   * Clone a response data and store it in sessionStorage
   * Does not support data other than json, Cache only json
   */
  const contentType = response.headers.get('Content-Type');
  if (contentType && contentType.match(/application\/json/i)) {
    // All data is saved as text
    response
      .clone()
      .text()
      .then((content) => {
        sessionStorage.setItem(hashcode, content);
        sessionStorage.setItem(`${hashcode}:timestamp`, Date.now());
      });
  }
  return response;
};

/**
 * Requests a URL, returning a promise.
 *
 * @param  {string} url       The URL we want to request
 * @param  {object} [option] The options we want to pass to "fetch"
 * @return {object}           An object containing either "data" or "err"
 */
export default function request(url, option) {
  const options = {
    expirys: isAntdPro(),
    ...option,
  };
  /**
   * Produce fingerprints based on url and parameters
   * Maybe url has the same parameters
   */
  const fingerprint = url + (options.body ? JSON.stringify(options.body) : '');
  const hashcode = hash
    .sha256()
    .update(fingerprint)
    .digest('hex');

  const defaultOptions = {
    credentials: 'include',
  };
  const newOptions = { ...defaultOptions, ...options };
  if (
    newOptions.method === 'POST' ||
    newOptions.method === 'PUT' ||
    newOptions.method === 'DELETE'
  ) {
    if (!(newOptions.body instanceof FormData)) {
      newOptions.headers = {
        Accept: 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
        ...newOptions.headers,
      };
      newOptions.body = JSON.stringify(newOptions.body);
    } else {
      // newOptions.body is FormData
      newOptions.headers = {
        Accept: 'application/json',
        ...newOptions.headers,
      };
    }
  }

  const expirys = options.expirys && 60;
  // options.expirys !== false, return the cache,
  if (options.expirys !== false) {
    const cached = sessionStorage.getItem(hashcode);
    const whenCached = sessionStorage.getItem(`${hashcode}:timestamp`);
    if (cached !== null && whenCached !== null) {
      const age = (Date.now() - whenCached) / 1000;
      if (age < expirys) {
        const response = new Response(new Blob([cached]));
        return response.json();
      }
      sessionStorage.removeItem(hashcode);
      sessionStorage.removeItem(`${hashcode}:timestamp`);
    }
  }
  return fetch(url, newOptions)
    .then(checkStatus)
    .then(response => cachedSave(response, hashcode))
    .then((response) => {
      // DELETE and 204 do not return data by default
      // using .json will report an error.
      if (newOptions.method === 'DELETE' || response.status === 204) {
        return response.text();
      }
      return response.json();
    })
    .catch((e) => {
      const status = e.name;
      if (status === 401) {
        // @HACK
        /* eslint-disable no-underscore-dangle */
        window.g_app._store.dispatch({
          type: 'login/logout',
        });
        return;
      }
      // environment should not be used
      // if (status === 403) {
      //   router.push('/exception/403');
      //   return;
      // }
      // if (status <= 504 && status >= 500) {
      //   router.push('/exception/500');
      //   return;
      // }
      // if (status >= 404 && status < 422) {
      //   router.push('/exception/404');
      // }
    });
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章