DEV Community

Ice Calee
Ice Calee

Posted on • Edited on

Convert Img url to File (axios, Vue js)

I had to check if there is an image, if not I have to assign an image at the registration of a new item, and send it with Axios as "Content-Type": "multipart/form-data",

First:
uploaded img to public/img/ folder : img_default.jpg

Second:
imported at src/views/CelebMain/ : import ImgDefault from "@image/img_default.jpg";

or in a code block below add
const ImgDefault= = "/img/img_default.jpg;

Third:
@views/CelebMain :

async convertURLtoFile (url) {
    const response = await fetch(url);
    const data = await response.blob();
    const filename = url.split("/").pop(); // url 구조에 맞게 수정할 것
    const metadata = { type: `image/jpeg` };
    return new File([data], filename!, metadata);
  };
Enter fullscreen mode Exit fullscreen mode

at registration - code below

async createCategoryMainItem() {
    // @ts-ignore
    this.editedCategoryMainItem = {
      ...this.editedCategoryMainItem,
      categoryType: 'CELEB'
    }
    // @ts-ignore
    if (this.$refs["main-form"].validate()) {
      this.setDate();

      if (this.checkDrawDateStr()) {
        this.drawSetDate();
      }
      const defaultImage = await this.convertURLtoFile(ImgDefault)
      if(!this.editedCategoryMainItem.fileBannerImage ||
        !this.editedCategoryMainItem.fileBigImage) {
        this.editedCategoryMainItem.fileBannerImage = defaultImage;
        this.editedCategoryMainItem.fileBigImage = defaultImage;
      }
      console.log('img', this.editedCategoryMainItem.fileBannerImage,this.editedCategoryMainItem.fileBigImage  )
      this.editedCategoryMainItem.bannerColor =
        this.editedCategoryMainItem.bannerColor.charAt(0) === "#"
          ? this.editedCategoryMainItem.bannerColor
          : "#" + this.editedCategoryMainItem.bannerColor;
      //프로덕션 어드민용 컨폼메세지
      if (this.editedCategoryMainItem.appPublishId === 1) {
        // @ts-ignore
        const ok = await this.$refs["confirm"].open(
          "Confirm",
          `저장하시겠습니까?`
        )
        if (ok) {
          const response = await registerCategoryMainItem(
            this.editedCategoryMainItem
          );
          if (response.status === 201) {
            await this.getCategoryMains();
            this.closeCategoryMainDialog();
          }
        }
      } else {
        const response = await registerCategoryMainItem(
          this.editedCategoryMainItem
        );
        if (response.status === 201) {
          await this.getCategoryMains();
          this.closeCategoryMainDialog();
        }
      }
    } else {
      // @ts-ignore
      this.$toast.error("필수 입력 필드를 입력하세요.");
    }
  }
Enter fullscreen mode Exit fullscreen mode
  • I learned a lot.

but before, we found an article on google, which helped to resolve convertation from url to file

image url을 file object로 변경하기 위해서 구글링을 해봤는데 생각보다 간단하게 했다.

export const convertURLtoFile = async (url: string) => {
  const response = await fetch(url);
  const data = await response.blob();
  const ext = url.split(".").pop(); // url 구조에 맞게 수정할 것
  const filename = url.split("/").pop(); // url 구조에 맞게 수정할 것
  const metadata = { type: `image/${ext}` };
  return new File([data], filename!, metadata);
};
Enter fullscreen mode Exit fullscreen mode

위의 함수를 사용하면 File object로 변경된다.

filename, ext를 구하기 위해서 저렇게 한 이유는 url의 형태가 http://abc.com/filename.ext이기 때문에 split('/')을 사용해서 문자열을 분리하고, 마지막 요소를 가져오면 filename이 된다.
array.length-1을 이용해서 마지막 요소를 가져오면 변수가 1~2개가 증가해서 pop 메소드를 사용했다. 물론 undefined가 리턴되기 때문에 File 생성자에서 filename에 !를 사용해서 undefined가 되는 경우를 무시했다. url 자체가 잘못되는 경우가 없기 때문이다.

Top comments (0)