file-uploader.js 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. import {wxToPromise} from "./wx";
  2. import config from "../model/config";
  3. import Http from "./http";
  4. import Route from "../model/route";
  5. import User from "../model/user";
  6. class FileUploader extends Http {
  7. static async upload(filePath, key = 'file',
  8. errorHandler = async (code, msg) => {
  9. if (code == 401) {
  10. await User.logout();
  11. Route.redirectLogin();
  12. }
  13. const title = Http._showError(code, msg)
  14. throw new Error(title)
  15. }) {
  16. let res
  17. try {
  18. res = await wxToPromise('uploadFile', {
  19. url: `${config.API}/v1/file`,
  20. filePath: filePath,
  21. name: key,
  22. })
  23. } catch (e) {
  24. console.log(e)
  25. await errorHandler(-100)
  26. }
  27. const serverData = JSON.parse(res.data)
  28. if (res.statusCode !== 201) {
  29. await errorHandler(serverData.code, serverData.msg)
  30. }
  31. return serverData.data
  32. }
  33. }
  34. export default FileUploader