Git Product home page Git Product logo

johndatserakis / file-upload-with-preview Goto Github PK

View Code? Open in Web Editor NEW
464.0 464.0 99.0 4.87 MB

๐Ÿ–ผ Simple file-upload utility that shows a preview of the uploaded image. Written in TypeScript. No dependencies. Works well with or without a framework.

Home Page: https://johndatserakis.github.io/file-upload-with-preview

License: MIT License

JavaScript 0.27% HTML 3.99% SCSS 6.38% TypeScript 89.36%
file image input javascript preview typescript upload

file-upload-with-preview's People

Contributors

danceswithcode avatar deniseileen avatar eytanproxi avatar firstor avatar johndatserakis avatar kozintsev avatar lex111 avatar pinceladasdaweb avatar tasinttttttt avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

file-upload-with-preview's Issues

Clear button is not working

Hello

I'm using your library. fileUploadWithPreview:imagesAdded works. fileUploadWithPreview:imageDeleted works.

But fileUploadWithPreview:clearButtonClicked is not getting fired.

I use custom-file-container__image-clear as the class of the clear button. I have not change any HTML structure.

What should I do?

Node js environment "Element is not defined"

Hello team -

Thanks for your work! I'm trying to use this in a Node environment. But get the error:
"myDirectory\node_modules\file-upload-with-preview\dist\file-upload-with-preview.umd.js:807
if (!Element.prototype.matches) {
^
ReferenceError: Element is not defined "

Here's my HTML.
`

...

    <!-- You'll want to make sure to at least set a width on the -->
    <!-- .custom-file-container class... -->
    ...
</head>
<body>

    ...

    <div class="custom-file-container" data-upload-id="myUniqueUploadId">
        <label>Upload File <a href="javascript:void(0)" class="custom-file-container__image-clear" title="Clear Image">&times;</a></label>

        <label class="custom-file-container__custom-file" >
            <input type="file" class="custom-file-container__custom-file__custom-file-input" accept="*" multiple aria-label="Choose File">
            <input type="hidden" name="MAX_FILE_SIZE" value="10485760" />
            <span class="custom-file-container__custom-file__custom-file-control"></span>
        </label>
        <div class="custom-file-container__image-preview"></div>
    </div>

    ...

    <script src="https://unpkg.com/[email protected]/dist/file-upload-with-preview.min.js"></script> 

    <script>
        var upload = new FileUploadWithPreview('myUniqueUploadId', {
            showDeleteButtonOnImages: true,
            text: {
                chooseFile: 'Custom Placeholder Copy',
                browse: 'Custom Button Copy',
                selectedCount: 'Custom Files Selected Copy',
            },
            images: {
                baseImage: importedBaseImage,
            },
            presetFiles: [
                '../public/logo-promosis.png',
                'https://images.unsplash.com/photo-1557090495-fc9312e77b28?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=668&q=80',
            ],
        })
    </script> 

</body>
`

Thanks for helping me solve this!
Elijah

Multiple image

when uploaded multiple files it will overlap first one only. not able to see multiple image

Default Preview Image

I have setup a custom default preview image using the method you posted about here: #5

I have managed to set that up with no issue.
The problem comes in when a user clicks the "X" to remove the image (either before or after an image has been selected) - the preview image defaults back to the original image and not the one I setup as the image to use.

I am assuming I should perhaps replace the default image value in the .js file, but not entirely sure how to do that.

Not able to get the image name on server through AXIOS

I'm having similar issue like #28. Sorry, i couldn't find my solution there. I need the file name but i'm only getting [token]. And in my case i have to make it done only by using AXIOS.
My code:
HTML:

<div class="wrapper">
	<div class="custom-file-container" data-upload-id="purchased_bills">
		<label>Image for purchase bill <a href="javascript:void(0)" class="custom-file-container__image-clear" title="Clear Image">x</a></label>
		<label class="custom-file-container__custom-file">
		    <input type="file" class="custom-file-container__custom-file__custom-file-input" accept="*" multiple>
		    <input type="hidden" name="MAX_FILE_SIZE" value="10485760" />
		    <span class="custom-file-container__custom-file__custom-file-control"></span>
		</label>
		<div class="custom-file-container__image-preview"></div>
	</div>
</div>

SCRIPTS:
I have created constructor to pass all the data through Axios which works well for other fields.

savePurchase() {
        this.purchase.upload = JSON.stringify(this.upload.cachedFileArray)
        console.log(this.upload.cachedFileArray)
        Axios.post('/product/purchase', this.purchase).then(resp => {
	  console.log(resp)
	}).catch(error => {
	  console.log(error.toJSON())
	})
}

BACKEND PART:

public function store(Request $request)
{
    return $request->all();
}

OUTPUTS:
console of cachedFileArray looks fine:

0: File { token: "lm50gxk1tka25mv2fdw0sj", name: "BYD-Auto-Logo.png", lastModified: 1577735432000, โ€ฆ }
โ€‹
1: File { token: "96gijmylpne8m06m1p1in4", name: "Datsun-logo.png", lastModified: 1577735432000, โ€ฆ }
โ€‹
2: File { token: "ghk8eojyoyxqp56k0dumc", name: "footer.png", lastModified: 1590848180800, โ€ฆ }

Console of response from server only returns token data, is there any way to get the file name by token ID? Or i have problem with my above codes?

[{"token":"lm50gxk1tka25mv2fdw0sj"},{"token":"96gijmylpne8m06m1p1in4"},{"token":"ghk8eojyoyxqp56k0dumc"}]

Thank you!

Clear on form reset

If the containing form gets reset with form.reset() or a <button type="reset">, then the underlying <input type="file"> is emptied but the preview still shows the old file. Seems a form reset doesn't trigger a change event, at least on Chrome.

It's easy enough to work around with something like:-

fu = new FileUploadWithPreview('image-upload');
fu.input.form.addEventListener('reset', fu.clearImagePreviewPanel.bind(fu));

I can submit a pull request to do this in bindClickEvents(), but not entirely convinced if it's necessarily sensible to do this by default.

(tested with 3.0.4)

ps: Thanks for your work!

PDF Upload Error Generated

When trying to upload a PDF (as opposed to an image), an error is generated in the console:

Failed to load resource: the server responded with a status of 404 (Not Found)

The file does get captured correctly and will upload successfully, but this error is generated when selecting the PDF to upload.

In addition, I assume generating a thumbnail preview of the PDF is not going to work - is there a way we could use a predefined image for when people upload a PDF?

Feature request: Change "X files selected" text

We can already enter our own strings for the browse button and choose files text.

It would be nice if we could also change the text "X files selected".
This way we could localize it for languages other than English.

Can i sort the array?

I mean If I've uploaded the files can i then reorder them through jquery sortable?

keep original image size in preview.

Hi, ran across this and trying it out. Thanks!

Using it for one image to test,

If I choose a small image height x width the preview displays/fills the entire preview area. This could make it blurry.

I may find this, but thought I'd give a quick ask,

Is there a way to keep the original image size in the preview area? Get the original image dimensions?

Thanks much! Appreciate it.

Didn't see this in the notes.

Best,

There is no name attribute to get the image on backed

Hi, I was using this utility to upload a profile image but there is no name attribute to get the image on backend (I am using codeigniter on backend). and when I did set it (name attribute) I was getting en empty array with no attributes (like size, name etc).

Beginner overloaded

Please can you create an easy and simple example to run the upload and then use the uploaded file for beginner with nothing more than a webserver, jquery und nothing more (at this step). I dont have npm (and wont use it), because its over-overloaded for a simple upload at my own server for me only. Thanks Bfo

FileUploadWithPreview is not a constructor (extended with examples)

My project structure (as simple as it gets, from Webpack manual)

image

The fileupload.js contents:

import {FileUploadWithPreview} from "file-upload-with-preview";
const hippo = new FileUploadWithPreview("myFirstImage");

The index.html:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>Getting Started</title>
</head>
<body>
<div class="custom-file-container" data-upload-id="myFirstImage"></div>
<script src="fileupload.js"></script>
</body>
</html>

Package.json:

"devDependencies": {
    "file-upload-with-preview": "^5.0.6",
    "webpack": "^5.72.0",
    "webpack-cli": "^4.9.2"
  },

And the result is
Uncaught TypeError: file_upload_with_preview__WEBPACK_IMPORTED_MODULE_0__.FileUploadWithPreview is not a constructor

PhpStorm syntax highlighting works fine. Import in head works fine, but I'd like to push it this way. It stems from my Laravel experience. I isolated the case from Laravel Mix down to the simplest example.

Using the clear button does not trigger image delete event

As the title says. I assume this is intentional since the event is probably meant to trigger on individual image deletion. Don't know if it'd be worth adding an event for when all the images are cleared, even programmatically. In the meantime I'm just looking for a click on elements with the "custom-file-container__image-clear" class to detect when the clear button is used.

Thanks for your work on this awesome plugin.

Logo

If there is an idea, I want to design a logo for you. I can volunteer if you want anything. What dou you say?

file_upload_with_preview__WEBPACK_IMPORTED_MODULE_4__.FileUploadWithPreview is not a constructor

Hello @johndatserakis ,
I am getting this error Uncaught TypeError: file_upload_with_preview__WEBPACK_IMPORTED_MODULE_4__.FileUploadWithPreview is not a constructor in ReactJs v18.2.0

"file-upload-with-preview": "^5.0.8",

Here is my sample code

import "file-upload-with-preview/dist/file-upload-with-preview.min.css";
import { FileUploadWithPreview } from "file-upload-with-preview";

import React, { useState } from "react";

function Gallery() {

  if (typeof window !== "undefined") {
    const upload = new FileUploadWithPreview("file-upload", {
      multiple: true,
    });
  }

  return (
    <div
    class="custom-file-container"
    data-upload-id="file-upload"
  ></div>
    );

}

How do i enable `cachedFileArray`

Am unable to remove file from input after adding it, in same way i cant add file when there is file in input.

https://stackoverflow.com/questions/59195429/unable-to-add-or-remove-image-from-multiple-html-input-field?noredirect=1#comment104610264_59195429

So how do i enable upload.cachedFileArray

var upload = new FileUploadWithPreview('myUniqueUploadId', {
  maxFileCount: 4,
  text: {
    chooseFile: 'Maximum 4 Images Allowed',
    browse: 'Add More Images',
    selectedCount: 'Files Added',
  },
});

gives error

ReferenceError: Element is not defined
at /home/runner/aurora/node_modules/file-upload-with-preview/dist/file-upload-with-preview.umd.js:854:2
at /home/runner/aurora/node_modules/file-upload-with-preview/dist/file-upload-with-preview.umd.js:2:82
at Object. (/home/runner/aurora/node_modules/file-upload-with-preview/dist/file-upload-with-preview.umd.js:5:2)
at Module._compile (internal/modules/cjs/loader.js:999:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1027:10)
at Module.load (internal/modules/cjs/loader.js:863:32)
at Function.Module._load (internal/modules/cjs/loader.js:708:14)
at Module.require (internal/modules/cjs/loader.js:887:19)
at /home/runner/aurora/index.js:4:31
at Script.runInContext (vm.js:130:18)

Name attribute not present in sending request to server.

Hi, I am having an issue that input element attribute name is not present in the dynamically generated field which is causing problems in the server side, then I tried attaching dynamically to it using the Custom JS it gets attached to the input element but still I can not receive the image on the server side, so could you elaborate how to work around with this, thanks for your help, your plugin has been a big help.

Only saving last image of multiple uploads

If multiple images are uploaded one at a time only the last image you upload will show up in Request.Files.

Upload a three images by selecting them individually. You will see the previews in the preview window.

When you check Request.Files it will only have the last image you uploaded not the previous two.

Unable to Replace background image for image grid

I want to replace default base64 image with backgroundImage base64

here is the script i use

   var upload = new FileUploadWithPreview('myUniqueUploadId', {
            maxFileCount: 4,
            text: {
                chooseFile: 'Maximum 4 Images Allowed',
                browse: 'Add More Images',
                selectedCount: 'Files Added',
            },
            images: {
                baseImage: backgroundImage,
            },
        })

but it doesn't work, How do i display backgroundImage

Delete several images in one loop

Is there any way to delete several images in one loop?
`let deletePhoto = (token, currentIndex) => {

    let selectedFileIndex = uploads[currentIndex].cachedFileArray.findIndex(function (x) {
        return x.token === token;
    });

    uploads[currentIndex].deleteFileAtIndex(selectedFileIndex);
};`

for (let token of tokens) { deletePhoto(token, currentIndex); }

If i choose only one preview - everything is working great, but if I choose more than one - currentFilesCount is correct, cachedFileArray - correct, but preview block multiplying images and working incorrectly

svg default images?

It would be really nice if we could use svg instread of png. Both for HD displays and file size.

Delete Button

We got two button 1 delete and another one clear .
1 Delete button only work or seen by multiple image not one .
1 Clear button i mistaken as deleted button which not listen to imageDeleted .

Multiple file input. Images still in $_FILES after deleting.

I have found bug probably.
Case 1:

  • add 3 files one by one in multiple file input
  • delete 2 of them
  • save form
  • expected results: 1 record in database. Test passed

Case 2:

  • add 3 files at the same time (using crtrl/cmnd button) in multiple file input
  • delete 2 of them
  • save form
  • expected results: 1 record in database. Actual: 3 records. Test FAILED

Case 3:

  • add 3 files at the same time (using crtrl/cmnd button) in multiple file input
  • delete all of them
  • save form
  • expected results: 0 records in database. Test PASSED.

Something is wrong here. Please let me know it is an issue and solve it or close this ticket if it is not

bug on chooseFile label

If I click on remove, the label come back to default text, not keeping the text I've chosen on options parameter. Example:

image

image

After click on X
image

[FEATURE] Ability to set a "main image"

Hi,

It would be very handy if we could set the "main image" from the preview of the images that we just uploaded.

For example. Let's say that we have a product_new page, where we use it to create the product page in our CRUD. In the image section, we can select multiples images to be uploaded. During the preview, it would be nice if we could select/tag one image to be the "main image" of the product. This is a common setup in ecommerce websites. You have the main product image and the rest are used for carousel or gallery. You could add a hover on the image, and on the left/right top corner a label/button/icon saying "set main image" or something like that. It would be like a radio element. You can only set one main image. Now, I just don't know how you could upload/submit them to the server. Maybe the main image can create a hidden input for it? But I would need a way to differentiate the main image from the others.

I hope I made it clear.

Cheers.

Use in Next js and Tailwind

Hi John

I've been trying to use this in Next js with Tailwind. But that doesn't accept this:
<div class="custom-file-container" data-upload-id="myFirstImage"></div>

I get the following error:
"Type '{ class: string; "data-upload-id": string; }' is not assignable to type 'DetailedHTMLProps<HTMLAttributes, HTMLDivElement>'.
Property 'class' does not exist on type 'DetailedHTMLProps<HTMLAttributes, HTMLDivElement>'. Did you mean 'className'?ts(2322)"

Do you have example code how to use this in Next js and Tailwind?

Thanks,
Murphy

Not able to get the image on server.

My html

<input type="hidden" name="upload_log" id="upload-log" value="" />
   <div class="upload-log-images">
   <div class="custom-file-container" data-upload-id="upload-log-images">
     <label>Upload File <a href="javascript:void(0)" class="custom-file-container__image-clear" title="Clear Image">&times</a></label>
     <label class="custom-file-container__custom-file" >
         <input type="file" class="custom-file-container__custom-file__custom-file-input" accept=".png, .jpg, .jpeg" multiple>
        <input type="hidden" name="MAX_FILE_SIZE" value="10485760" />
       <span class="custom-file-container__custom-file__custom-file-control"></span>
      </label>
      <div class="custom-file-container__image-preview"></div>
        </div>
  </div>

What i understood is i have all the valid images in cachedFileArray.

I am trying to sending complete array in hidden input.

window.addEventListener('fileUploadWithPreview:imageDeleted', function(e) {
    if (e.detail.uploadId === 'upload-log-images') {
        jQuery('#upload-log').val(JSON.stringify(e.detail.cachedFileArray))
    }
})

At the server level.

 $files =   $upload_log = json_decode(utf8_encode(stripslashes($_POST['upload_log'])), true);

output is

Array
(
    [0] => Array
        (
            [token] => pvf6dfs1p65k520olz9r
        )

    [1] => Array
        (
            [token] => 3tii69591shepm5x6apzys
        )

)

Uncaught TypeError: FileUploadWithPreview is not a constructor

Hello, I'm having the same problem (#19) importing from NPM into a JS file.

File plugins.js using webpack:

window.FileUploadWithPreview = require('file-upload-with-preview');

When I see in the browser, the error appears:

Uncaught TypeError: FileUploadWithPreview is not a constructor

My script into HTML

<script src="js/plugins.js" type="text/javascript"></script>
<script type="application/javascript">
        const upload = new FileUploadWithPreview('uploadImage', { text: {chooseFile: 'Selecione um arquivo', browse: 'Selecionar'} });
</script>

Save in local storage

I would like to know if there is an option to save the images in localstorage and then add them to each input.

Id

I'm trying to upload file, but I got the error below.
I am accessing the id with:

<div class="custom-file-container" data-upload-id="myPdf">
            <label>Upload File <a href="javascript:void(0)" class="custom-file-container__image-clear" title="Clear Image">x</a></label>
            <label class="custom-file-container__custom-file" >
                <input type="file" @change="addPdf()" class="custom-file-container__custom-file__custom-file-input" accept="*">
                <input type="hidden" name="MAX_FILE_SIZE" value="10485760" />
                <span class="custom-file-container__custom-file__custom-file-control"></span>
            </label>
            <div class="custom-file-container__image-preview"></div>
        </div>

in the script section of my vue:

saveBook() {
          let p = document.getElementById('myPdf')
          let upload = new FileUploadWithPreview(p);
          console.log(upload);

}
app.js:46935 Uncaught Error: No uploadId found. You must initialize file-upload-with-preview with a unique uploadId.
at new Q (app.js:46935)
at VueComponent.saveBook (app.js:46744)
at Proxy.boundFn (app.js:34294)
at submit (app.js:46970)
at invoker (app.js:36051)
at HTMLFormElement.fn._withTask.fn._withTask (app.js:35886)

Please, how can I resolve it, or is there something I'm missing?

Thanks

Image Preview DIV position

Is there any way to place the image preview DIV somewhere else on the page - as opposed to directly underneath the input box?

I would like the image preview to appear to the right of the input box, but when I try to move the DIV, an error is generated.

I can only assume this is due to the fact that the code expects to find the preview DIV being held within the larger custom-file-container DIV.

maxCount

maxCount doesn't working to limit the images uploads. Can you give an example how to write the script.?
Screenshot from 2019-11-14 18-28-34

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.