Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
              
            
!

CSS

              
                
              
            
!

JS

              
                const { createApp, version, ref, computed, watch } = Vue;

const el = document.createElement("div");
document.body.appendChild(el);

// upload component
const UploadField = {
  name: "UploadField",
  template: `<div>
        <button
            ref="fieldRef"
            type="button"
            class="
                flex items-center border border-gray-300
                rounded shadow
                w-full text-left
                overflow-hidden
                focus:outline-none
                focus-visible:ring focus-visible:ring-purple-600 focus-visible:ring-opacity-60
            "
            :class="classes"
            @click="handleFakeFieldClick()"
        >
            <span
                class="block px-3 py-1.5 flex-grow line-clamp-1"
                :class="{
                    'text-gray-700': displayValue,
                    'text-gray-500': !displayValue,
                }"
            >{{ displayValue ?? placeholder }}</span>
            <span class="bg-gray-800 border border-gray-800 text-white flex items-center px-3 py-1.5 flex-shrink-0 hover:opacity-75">
                <span class="block mr-2 sr-only">
                    {{ selectButtonLabel }}
                </span>
    <svg
        xmlns="http://www.w3.org/2000/svg"
        fill="none"
        viewBox="0 0 24 24"
        stroke="currentColor"
        class="w-6"
        aria-hidden
    >
        <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M5 19a2 2 0 01-2-2V7a2 2 0 012-2h4l2 2h4a2 2 0 012 2v1M5 19h14a2 2 0 002-2v-5a2 2 0 00-2-2H9a2 2 0 00-2 2v5a2 2 0 01-2 2z"
        />
    </svg>
            </span>
        </button>
        <input
            :id="id"
            ref="blindFieldRef"
            class="block absolute -top-full -left-full pointer-events-none invisible"
            tabindex="-1"
            type="file"
            :accept="accept"
            @change="imageChanged"
        >
    </div>`,
  inheritAttrs: false,
  props: {
    id: {
      type: String,
      required: false,
      default: null
    },
    modelValue: {
      type: File,
      required: false,
      default: null
    },
    error: {
      type: String,
      required: false,
      default: null
    },
    notRounded: {
      type: Boolean,
      required: false,
      default: false
    },
    placeholder: {
      type: String,
      required: false,
      default: null
    },
    handleAsImage: {
      type: Boolean,
      required: false,
      default: true
    },
    resize: {
      type: Boolean,
      required: false,
      default: false
    },
    maxHeight: {
      type: Number,
      required: false,
      default: 3000
    },
    maxWidth: {
      type: Number,
      required: false,
      default: 1500
    },
    minHeight: {
      type: Number,
      required: false,
      default: 400
    },
    minWidth: {
      type: Number,
      required: false,
      default: 150
    },
    maxSize: {
      type: Number,
      required: false,
      default: 50
    },
    mimetypes: {
      type: [String, Array],
      required: false,
      default: "*/*"
    },
    // blind (aria)
    selectButtonLabel: {
      type: String,
      required: false,
      default: "Select File"
    }
  },
  emits: ["update:modelValue", "previewUrlChanged", "change"],
  setup(props, { emit }) {
    const rawMimeTypes = props.mimetypes || "*/*";
    const accept = ref(
      Array.isArray(rawMimeTypes) ? rawMimeTypes.join(",") : rawMimeTypes
    );

    const displayValue = ref(null);

    /**
     * @type {Ref<?HTMLElement>}
     */
    const fieldRef = ref(null);

    /**
     * @type {Ref<?HTMLElement>}
     */
    const blindFieldRef = ref(null);

    const classes = computed(() => ({
      rounded: !props.notRounded,
      shadow: true,
      "bg-red-200 border-red-600 text-red-700 placeholder-red-700 placeholder-opacity-60 focus:ring-red-500": !!props.error
    }));

    function focus() {
      if (fieldRef.value && fieldRef.value.focus) {
        setTimeout(() => fieldRef.value.focus(), 300);
      }
    }

    function resizeImage(
      imageDataUrl,
      file,
      maxHeight,
      maxWidth,
      maxSize,
      recursion = 0
    ) {
      const { name, type } = file;

      const image = new Image();
      image.onload = function () {
        let width = image.width;
        let height = image.height;
        let needsResize = false;

        if (width > maxWidth) {
          height *= maxWidth / width;
          width = maxWidth;
          needsResize = true;
        }
        if (height > maxHeight) {
          width *= maxHeight / height;
          height = maxHeight;
          needsResize = true;
        }

        let targetValues;
        if (!needsResize) {
          if (
            (targetValues = shouldResize(
              imageDataUrl,
              file,
              maxHeight,
              maxWidth,
              maxSize,
              recursion
            )) === null
          ) {
            emitPreviewImageChangedIfNeeded(imageDataUrl);
            emitUpdated(file);
          } else {
            const { targetHeight, targetWidth } = targetValues;
            resizeImage(
              imageDataUrl,
              file,
              targetHeight,
              targetWidth,
              maxSize,
              recursion + 1
            );
          }
          return;
        }

        const canvas = document.createElement("canvas");

        canvas.width = width;
        canvas.height = height;
        // noinspection JSCheckFunctionSignatures
        canvas.getContext("2d").drawImage(image, 0, 0, width, height);

        canvas.toBlob((blob) => {
          const dataUrl = canvas.toDataURL(type);
          const file = new File([blob], name, {
            type
          });
          if (
            (targetValues = shouldResize(
              dataUrl,
              file,
              maxHeight,
              maxWidth,
              maxSize,
              recursion
            )) !== null
          ) {
            const { targetHeight, targetWidth } = targetValues;
            resizeImage(
              dataUrl,
              file,
              targetHeight,
              targetWidth,
              maxSize,
              recursion + 1
            );
            return;
          }
          emitPreviewImageChangedIfNeeded(dataUrl);
          emitUpdated(file);
        }, type);
      };
      image.src = imageDataUrl;
    }

    /**
     * @param {string} dataUrl
     * @param {File} file
     * @param {Number} maxHeight
     * @param {Number} maxWidth
     * @param {Number} maxSize
     * @param {number} recursion
     *
     * @return {?{targetHeight: Number, targetWidth: Number}}
     */
    function shouldResize(
      dataUrl,
      file,
      maxHeight,
      maxWidth,
      maxSize,
      recursion = 0
    ) {
      if (file.size > maxSize && recursion < 20) {
        const rawFactor = maxSize / file.size;
        const factor =
          rawFactor < 0.74 ? rawFactor + 0.25 : Math.min(rawFactor, 0.99);
        const targetHeight = Math.round(maxHeight * factor);
        const targetWidth = Math.round(maxWidth * factor);

        if (
          props.minHeight &&
          props.minHeight <= targetHeight &&
          props.minWidth &&
          props.minWidth <= targetWidth
        ) {
          return {
            targetHeight,
            targetWidth
          };
        }
      }
      return null;
    }

    function handleImage(origImageSrc, file) {
      if (file.type === "image/svg+xml") {
        // do not resize svg images
        emitPreviewImageChangedIfNeeded(origImageSrc);
        emitUpdated(file);
        return;
      }
      const maxHeight = props.maxHeight || 800;
      const maxWidth = props.maxWidth;
      const maxSize = props.maxSize;

      resizeImage(origImageSrc, file, maxHeight, maxWidth, maxSize);
    }

    /**
     * @param {?String} dataUrl
     */
    function emitPreviewImageChangedIfNeeded(dataUrl = null) {
      if (!props.handleAsImage) {
        return;
      }
      emit("previewUrlChanged", dataUrl);
    }

    /**
     * @param {File} file
     */
    function emitUpdated(file) {
      emit("update:modelValue", file);
      emit("change");
    }

    function readURL(input) {
      if (input.files && input.files[0]) {
        const reader = new FileReader();

        reader.onload = function (ev) {
          if (props.handleAsImage) {
            handleImage(ev.target.result, input.files[0]);
          } else {
            emitUpdated(input.files[0]);
          }
        };

        reader.readAsDataURL(input.files[0]);
      } else {
        emitPreviewImageChangedIfNeeded();
      }
    }

    function imageChanged(ev) {
      const newValue =
        ev.target.files && ev.target.files[0] ? ev.target.files[0] : null;
      displayValue.value = newValue
        ? ev.target.value.replace(/^.+\\/, "")
        : null;

      readURL(ev.target);
    }

    function handleFakeFieldClick() {
      if (!blindFieldRef.value) {
        return;
      }
      blindFieldRef.value.click();
    }

    watch(
      () => props.modelValue,
      (newValue) => {
        if (newValue === null) {
          displayValue.value = null;
        }
      }
    );

    return {
      accept,
      classes,
      displayValue,
      fieldRef,
      blindFieldRef,
      focus,
      imageChanged,
      handleFakeFieldClick
    };
  }
};

// example with a simple form
const Root = {
  components: {
    UploadField
  },
  template: `<div class="p-4">
    <h1 class="text-2xl font-bold mb-3">Upload Field Demo</h1>
    <form class="max-w-screen-sm" @submit.prevent="submitForm">
    <div class="grid gap-4 sm:grid-cols-2">
                <div
                class="w-full min-w-32 min-h-40 max-w-72 mx-auto sm:ml-0 sm:mr-auto"
            >
                <div
                    v-if="imageUrl"
                >
                    <div
                        v-if="isPreview"
                        class="text-gray-500"
                    >
                        Preview
                    </div>
                    <img
                        class="block max-w-full"
                        :src="imageUrl"
                        alt="Profile Image"
                    />
                </div>
                <div
                    v-else
                    class="bg-gray-300 aspect-h-4 aspect-w-3"
                >
                    <div class="flex items-center justify-center">
                        <div class="text-2xl lg:text-3xl font-black opacity-40 uppercase ">
                            Placeholder
                        </div>
                    </div>
                </div>
            </div>
    <div class="flex items-center space-x-2 self-start">
      <label for="upload">Select File</label>
      <upload-field 
      class="w-full block"
      id="upload"
      placeholder="Please select a file"
      :mimetypes="mimetypes"
      :handle-as-image="true"
      :max-size="maxSize"
      :resize="true"
      :max-width="800"
      @previewUrlChanged="handlePreviewUrlChanged"
      />
    </div>
</div>
      <div class="text-right mt-4">
        <button type="submit"
        class="inline-block bg-black px-3 py-2 text-white rounded shadow"
        :disabled="btnDisabled"
                :class="{
                    'cursor-not-allowed opacity-40': btnDisabled,
                    'hover:opacity-75': !btnDisabled,
                }"
        >Submit</button>
        </div>
    </form>
    </div>`,
  setup() {
    const mimetypes = ref([
      "image/png",
      "image/jpeg",
      "image/svg+xml",
      "image/svg"
    ]);

    const maxSize = ref(30720000); // 300kb

    const file = ref(null);

    const imageUrl = ref(null);
    const isPreview = computed(() => !!imageUrl.value);
    const btnDisabled = computed(() => !imageUrl.value)

    function submitForm() {
      console.log("submitForm", file.value);
      /**
      const url = "https://example.com/uploadPhoto";
      const formData = new FormData();
      formData.append("profile_photo", file.value);
      axios.post(url, formData)
        .then(....)
        ...
      */
    }

    function handlePreviewUrlChanged(previewImageUrl) {
      imageUrl.value = previewImageUrl;
    }

    return {
      submitForm,
      mimetypes,
      maxSize,
      file,
      imageUrl,
      isPreview,
      handlePreviewUrlChanged,
      btnDisabled,
    };
  }
};


createApp(Root).mount(el)

              
            
!
999px

Console