Dropzone - 이미지 & 파일 업로드 (드래그 앤 드롭) 라이브러리

Dropzone.js는 프론트 페이지에서 사용하는 대표적인 파일 업로드 라이브러리이다.

기본적으로 드래그 앤 드롭 기능을 지원하며, 라이브러리 기본 스타일 또한 동적인 애니메이션과 고급스러운 파일 첨부 상호작용이 매우 훌륭하다. (테마 역시 커스텀 수정이 가능하다)

특히 이미지 파일을 업로드할때, 기본적으로 이미지 썸네일 미리보기를 지원하며 멀티 업로드 기능 역시 지원한다.

Amazon S3 멀티파트 업로드도 지원한다고 한다.

Dropzone.js

긴말 필요없이, 아래 코드 실행 예제를 보고 이미지 파일들을 업로드 해보자.


Dropzone 사용법

postcard-title
github.com
Dropzone is an easy to use drag'n'drop library. It supports image previews and shows nice progress bars. - GitHub - dropzone/dropzone: Dropzone is an easy to use drag'n'drop library...
shell
$ npm install dropzone # 노드

$ yarn add dropzoneCopy
html
<!-- 클라이언트 소스 로드 -->
<script src="https://unpkg.com/dropzone@5/dist/min/dropzone.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/dropzone@5/dist/min/dropzone.min.css" type="text/css"/>Copy

 

form 태그

form 태그에 class="dropzone" 을 명시해주면, 자동으로 파싱되서 드롭존 영역이 생성된다.

그리고 Dropzone.options.myDropzone 에 옵션 인자를 주면 된다.

html
<!-- 드롭존을 적용할 클래스이름을 dropzone 해야 css테마가 적용된다 -->
<form action="/target" class="dropzone" id="myDropzone"></form>

<script>
  Dropzone.discover(); // deprecated 된 옵션. false로 해놓는걸 공식문서에서 명시
  Dropzone.options.myDropzone = { // form.dropzone 의 id값을 명시. 만일 my-dropzone 이라고 id를 명시해도 자동으로 camel-case로 변경된다.
  	url: "https://httpbin.org/post",
    method: 'post',
	// ... 옵션
  };
</script>Copy

 

자바스크립트 클래스

만일 form 태그를 쓰지않으면, div 태그를 선언하고 new Dropzone() 생성자를 통해 자동으로 드롭존 영역을 생성할수도 있다.

html
<!-- 드롭존을 적용할 클래스이름을 dropzone 해야 css테마가 적용된다 -->
<div class="dropzone"></div>

<script>
	Dropzone.autoDiscover = false;  // deprecated 된 옵션. false로 해놓는걸 공식문서에서 명시
    const dropzone = new Dropzone("div.dropzone", { 
        url: "https://httpbin.org/post",
        method: 'post',
        // ... 옵션
    });
</script>

<script>
    // 제이쿼리도 지원
    $("div.dropzone").dropzone({ 
        url: "https://httpbin.org/post",
        method: 'post',
    });
</script>Copy

Dropzone 옵션

  • Dropzone의 기본설정은 파일을 올리는 순간 서버로 보낸다. 이를 방지하기 위해 옵션을 설정해 주어야 한다.
  • Dropzone에서 여러 개 파일을 동시에 올리는 것은 기본 값이 아니다. 이 역시 옵션으로 추가 설정해주어야 한다.
  • Dropzone에서 바로 보내므로 header 값을 설정해주어야 한다.
    만일 JWT를 사용할 경우에는 Bearer 토큰을 header에 붙여주어야 한다.
  • 중복된 파일을 올리지 못하게 막으려면 따로 함수를 붙여주어야 한다.
  • 새로운 파일을 추가할때만 파일을 보낼 수 있으므로, 만약 기존에 있던 파일이 남아있고 업데이트를 해주어야 하는 상황이라면 다른 방식으로 파일을 보내주어야 한다.
  • 파일의 용량이 클 경우 chunck로 파일을 일정 크기 만큼 쪼개서 업로드할 수 도 있다.
javascript
Dropzone.autoDiscover = false; // deprecated 된 옵션. false로 해놓는걸 공식문서에서 명시
const dropzone = new Dropzone('div.my-dropzone', {
  
   url: 'https://httpbin.org/post', // 파일을 업로드할 서버 주소 url.
   method: 'post', // 기본 post로 request 감. put으로도 할수있음
   headers: {
      // 요청 보낼때 헤더 설정
      Authorization: 'Bearer ' + token, // jwt
   },

   autoProcessQueue: false, // 자동으로 보내기. true : 파일 업로드 되자마자 서버로 요청, false : 서버에는 올라가지 않은 상태. 따로 this.processQueue() 호출시 전송
   clickable: true, // 클릭 가능 여부
   autoQueue: false, // 드래그 드랍 후 바로 서버로 전송
   createImageThumbnails: true, //파일 업로드 썸네일 생성

   thumbnailHeight: 120, // Upload icon size
   thumbnailWidth: 120, // Upload icon size

   maxFiles: 1, // 업로드 파일수
   maxFilesize: 100, // 최대업로드용량 : 100MB
   paramName: 'image', // 서버에서 사용할 formdata 이름 설정 (default는 file)
   parallelUploads: 2, // 동시파일업로드 수(이걸 지정한 수 만큼 여러파일을 한번에 넘긴다.)
   uploadMultiple: false, // 다중업로드 기능
   timeout: 300000, //커넥션 타임아웃 설정 -> 데이터가 클 경우 꼭 넉넉히 설정해주자

   addRemoveLinks: true, // 업로드 후 파일 삭제버튼 표시 여부
   dictRemoveFile: '삭제', // 삭제버튼 표시 텍스트
   acceptedFiles: '.jpeg,.jpg,.png,.gif,.JPEG,.JPG,.PNG,.GIF', // 이미지 파일 포맷만 허용

   init: function () {
      // 최초 dropzone 설정시 init을 통해 호출
      console.log('최초 실행');
      let myDropzone = this; // closure 변수 (화살표 함수 쓰지않게 주의)

      // 서버에 제출 submit 버튼 이벤트 등록
      document.querySelector('버튼').addEventListener('click', function () {
         console.log('업로드');

         // 거부된 파일이 있다면
         if (myDropzone.getRejectedFiles().length > 0) {
            let files = myDropzone.getRejectedFiles();
            console.log('거부된 파일이 있습니다.', files);
            return;
         }

         myDropzone.processQueue(); // autoProcessQueue: false로 해주었기 때문에, 메소드 api로 파일을 서버로 제출
      });

      // 파일이 업로드되면 실행
      this.on('addedfile', function (file) {
         // 중복된 파일의 제거
         if (this.files.length) {
            // -1 to exclude current file
            var hasFile = false;
            for (var i = 0; i < this.files.length - 1; i++) {
               if (
                  this.files[i].name === file.name &&
                  this.files[i].size === file.size &&
                  this.files[i].lastModifiedDate.toString() === file.lastModifiedDate.toString()
               ) {
                  hasFile = true;
                  this.removeFile(file);
               }
            }
            if (!hasFile) {
               addedFiles.push(file);
            }
         } else {
            addedFiles.push(file);
         }
      });

      // 업로드한 파일을 서버에 요청하는 동안 호출 실행
      this.on('sending', function (file, xhr, formData) {
         console.log('보내는중');
      });

      // 서버로 파일이 성공적으로 전송되면 실행
      this.on('success', function (file, responseText) {
         console.log('성공');
      });

      // 업로드 에러 처리
      this.on('error', function (file, errorMessage) {
         alert(errorMessage);
      });
   },
   
});Copy

Dropzone 커스텀 템플릿

만일 기본 스타일인 정사각형 모양으로 파일이 첨부되는 모양이 마음에 들지 않는다면, 이 역시 커스텀 할수 있다.

내가 원하는 모양으로 만들고 previewTemplate 옵션으로 적용해주면 된다.

 

다음은 커스텀 파일 첨부 템플릿 예시이다.

스타일 프레임워크로 부트스트랩5 를 사용했다.

html
<!-- 소스 로드 -->
<script src="https://unpkg.com/dropzone@5/dist/min/dropzone.min.js"></script>
<link rel="stylesheet" href="https://unpkg.com/dropzone@5/dist/min/dropzone.min.css" type="text/css" />
<!-- 부트스트랩5 -->
<link rel='stylesheet' href='https://cdnjs.cloudflare.com/ajax/libs/bootstrap/5.1.3/css/bootstrap.min.css' />

<!-- 드롭존 - 클릭영역 -->
<div class="dropzone"></div>

<!-- 파일첨부 영역 -->
<ul class="list-unstyled mb-0" id="dropzone-preview">
   <li class="mt-2" id="dropzone-preview-list">
      <!-- This is used as the file preview template -->
      <div class="border rounded-3">
         <div class="d-flex align-items-center p-2">
            <div class="flex-shrink-0 me-3">
               <div class="width-8 h-auto rounded-3">
                  <img data-dz-thumbnail="data-dz-thumbnail" class="w-full h-auto rounded-3 block" src="#"
                     alt="Dropzone-Image" style="width: 120px;" />
               </div>
            </div>
            <div class="flex-grow-1">
               <div class="pt-1">
                  <h6 class="font-semibold mb-1" data-dz-name="data-dz-name"> </h6>
                  <p class="text-sm text-muted fw-normal" data-dz-size="data-dz-size"></p>
                  <strong class="error text-danger" data-dz-errormessage="data-dz-errormessage"></strong>
               </div>
            </div>
            <div class="shrink-0 ms-3">
               <button data-dz-remove="data-dz-remove" class="btn btn-sm btn-danger">Delete</button>
            </div>
         </div>
      </div>
   </li>
</ul>

<script>
   Dropzone.autoDiscover = false;

   var dropzonePreviewNode = document.querySelector('#dropzone-preview-list'); // <li class="mt-2" id="dropzone-preview-list"> 부분을 가져와서
   dropzonePreviewNode.id = ''; // 중복 회피를 위해 id 없애고
   var previewTemplate = dropzonePreviewNode.parentNode.innerHTML; // 엘리먼트 전체를 저장 (템플릿)
   dropzonePreviewNode.parentNode.removeChild(dropzonePreviewNode); // 그리고 삭제

   const dropzone = new Dropzone(".dropzone", {
      url: "https://httpbin.org/post", // 파일을 업로드할 서버 주소 url. 
      method: "post", // 기본 post로 request 감. put으로도 할수있음

      previewTemplate: previewTemplate, // 만일 기본 테마를 사용하지않고 커스텀 업로드 테마를 사용하고 싶다면
      previewsContainer: '#dropzone-preview', // 드롭존 파일 나타나는 영역을 .dropzone이 아닌 다른 엘리먼트에서 하고싶을때
   });
</script>Copy

Dropzone 모든 옵션 정리

postcard-title
docs.dropzone.dev
If chunking is enabled, this defines whether **every** file should be chunked, even if the file size is below chunkSize. This means, that the additional chunk form data will be submitted and the chunksUploaded callback will be invoked.

 

Dropzone 옵션 인수

javascript
/**
 * Has to be specified on elements other than form (or when the form
 * doesn't have an `action` attribute). You can also
 * provide a function that will be called with `files` and
 * must return the url (since `v3.12.0`)
 */
url: null,

/**
 * Can be changed to `"put"` if necessary. You can also provide a function
 * that will be called with `files` and must return the method (since `v3.12.0`).
 */
method: "post",

/**
 * Will be set on the XHRequest.
 */
withCredentials: false,

/**
 * The timeout for the XHR requests in milliseconds (since `v4.4.0`).
 */
timeout: 30000,

/**
 * How many file uploads to process in parallel (See the
 * Enqueuing file uploads documentation section for more info)
 */
parallelUploads: 2,

/**
 * Whether to send multiple files in one request. If
 * this it set to true, then the fallback file input element will
 * have the `multiple` attribute as well. This option will
 * also trigger additional events (like `processingmultiple`). See the events
 * documentation section for more information.
 */
uploadMultiple: false,

/**
 * Whether you want files to be uploaded in chunks to your server. This can't be
 * used in combination with `uploadMultiple`.
 *
 * See [chunksUploaded](#config-chunksUploaded) for the callback to finalise an upload.
 */
chunking: false,

/**
 * If `chunking` is enabled, this defines whether **every** file should be chunked,
 * even if the file size is below chunkSize. This means, that the additional chunk
 * form data will be submitted and the `chunksUploaded` callback will be invoked.
 */
forceChunking: false,

/**
 * If `chunking` is `true`, then this defines the chunk size in bytes.
 */
chunkSize: 2000000,

/**
 * If `true`, the individual chunks of a file are being uploaded simultaneously.
 */
parallelChunkUploads: false,

/**
 * Whether a chunk should be retried if it fails.
 */
retryChunks: false,

/**
 * If `retryChunks` is true, how many times should it be retried.
 */
retryChunksLimit: 3,

/**
 * If not `null` defines how many files this Dropzone handles. If it exceeds,
 * the event `maxfilesexceeded` will be called. The dropzone element gets the
 * class `dz-max-files-reached` accordingly so you can provide visual feedback.
 */
maxFilesize: 256,

/**
 * The name of the file param that gets transferred.
 * **NOTE**: If you have the option  `uploadMultiple` set to `true`, then
 * Dropzone will append `[]` to the name.
 */
paramName: "file",

/**
 * In MB. When the filename exceeds this limit, the thumbnail will not be generated.
 */
maxThumbnailFilesize: 10,

/**
 * If `null`, the ratio of the image will be used to calculate it.
 */
thumbnailWidth: 120,

/**
 * The same as `thumbnailWidth`. If both are null, images will not be resized.
 */
thumbnailHeight: 120,

/**
 * How the images should be scaled down in case both, `thumbnailWidth` and `thumbnailHeight` are provided.
 * Can be either `contain` or `crop`.
 */
thumbnailMethod: 'crop',

/**
 * If set, images will be resized to these dimensions before being **uploaded**.
 * If only one, `resizeWidth` **or** `resizeHeight` is provided, the original aspect
 * ratio of the file will be preserved.
 *
 * The `options.transformFile` function uses these options, so if the `transformFile` function
 * is overridden, these options don't do anything.
 */
resizeWidth: null,

/**
 * See `resizeWidth`.
 */
resizeHeight: null,

/**
 * The mime type of the resized image (before it gets uploaded to the server).
 * If `null` the original mime type will be used. To force jpeg, for example, use `image/jpeg`.
 * See `resizeWidth` for more information.
 */
resizeMimeType: null,

/**
 * The quality of the resized images. See `resizeWidth`.
 */
resizeQuality: 0.8,

/**
 * How the images should be scaled down in case both, `resizeWidth` and `resizeHeight` are provided.
 * Can be either `contain` or `crop`.
 */
resizeMethod: 'contain',

/**
 * The base that is used to calculate the filesize. You can change this to
 * 1024 if you would rather display kibibytes, mebibytes, etc...
 * 1024 is technically incorrect, because `1024 bytes` are `1 kibibyte` not `1 kilobyte`.
 * You can change this to `1024` if you don't care about validity.
 */
filesizeBase: 1000,

/**
 * Can be used to limit the maximum number of files that will be handled by this Dropzone
 */
maxFiles: null,

/**
 * An optional object to send additional headers to the server. Eg:
 * `{ "My-Awesome-Header": "header value" }`
 */
headers: null,

/**
 * If `true`, the dropzone element itself will be clickable, if `false`
 * nothing will be clickable.
 *
 * You can also pass an HTML element, a CSS selector (for multiple elements)
 * or an array of those. In that case, all of those elements will trigger an
 * upload when clicked.
 */
clickable: true,

/**
 * Whether hidden files in directories should be ignored.
 */
ignoreHiddenFiles: true,

/**
 * The default implementation of `accept` checks the file's mime type or
 * extension against this list. This is a comma separated list of mime
 * types or file extensions.
 *
 * Eg.: `image/*,application/pdf,.psd`
 *
 * If the Dropzone is `clickable` this option will also be used as
 * [`accept`](https://developer.mozilla.org/en-US/docs/HTML/Element/input#attr-accept)
 * parameter on the hidden file input as well.
 */
acceptedFiles: null,

/**
 * **Deprecated!**
 * Use acceptedFiles instead.
 */
acceptedMimeTypes: null,

/**
 * If false, files will be added to the queue but the queue will not be
 * processed automatically.
 * This can be useful if you need some additional user input before sending
 * files (or if you want want all files sent at once).
 * If you're ready to send the file simply call `myDropzone.processQueue()`.
 *
 * See the [enqueuing file uploads](#enqueuing-file-uploads) documentation
 * section for more information.
 */
autoProcessQueue: true,

/**
 * If false, files added to the dropzone will not be queued by default.
 * You'll have to call `enqueueFile(file)` manually.
 */
autoQueue: true,

/**
 * If `true`, this will add a link to every file preview to remove or cancel (if
 * already uploading) the file. The `dictCancelUpload`, `dictCancelUploadConfirmation`
 * and `dictRemoveFile` options are used for the wording.
 */
addRemoveLinks: false,

/**
 * Defines where to display the file previews – if `null` the
 * Dropzone element itself is used. Can be a plain `HTMLElement` or a CSS
 * selector. The element should have the `dropzone-previews` class so
 * the previews are displayed properly.
 */
previewsContainer: null,

/**
 * Set this to `true` if you don't want previews to be shown.
 */
disablePreviews: false,

/**
 * This is the element the hidden input field (which is used when clicking on the
 * dropzone to trigger file selection) will be appended to. This might
 * be important in case you use frameworks to switch the content of your page.
 *
 * Can be a selector string, or an element directly.
 */
hiddenInputContainer: "body",

/**
 * If null, no capture type will be specified
 * If camera, mobile devices will skip the file selection and choose camera
 * If microphone, mobile devices will skip the file selection and choose the microphone
 * If camcorder, mobile devices will skip the file selection and choose the camera in <a href="https://www.jqueryscript.net/tags.php?/video/">video</a> mode
 * On apple devices multiple must be set to false.  AcceptedFiles may need to
 * be set to an appropriate mime type (e.g. "image/*", "audio/*", or "video/*").
 */
capture: null,

/**
 * **Deprecated**. Use `renameFile` instead.
 */
renameFilename: null,

/**
 * A function that is invoked before the file is uploaded to the server and renames the file.
 * This function gets the `File` as argument and can use the `file.name`. The actual name of the
 * file that gets used during the upload can be accessed through `file.upload.filename`.
 */
renameFile: null,

/**
 * If `true` the fallback will be forced. This is very useful to test your server
 * implementations first and make sure that everything works as
 * expected without dropzone if you experience problems, and to test
 * how your fallbacks will look.
 */
forceFallback: false,

/**
 * The text used before any files are dropped.
 */
dictDefaultMessage: "Drop files here to upload",

/**
 * The text that replaces the default message text it the browser is not supported.
 */
dictFallbackMessage: "Your browser does not support drag'n'drop file uploads.",

/**
 * The text that will be added before the fallback form.
 * If you provide a  fallback element yourself, or if this option is `null` this will
 * be ignored.
 */
dictFallbackText: "Please use the fallback form below to upload your files like in the olden days.",

/**
 * If the filesize is too big.
 * `{{filesize}}` and `{{maxFilesize}}` will be replaced with the respective configuration values.
 */
dictFileTooBig: "File is too big ({{filesize}}MiB). Max filesize: {{maxFilesize}}MiB.",

/**
 * If the file doesn't match the file type.
 */
dictInvalidFileType: "You can't upload files of this type.",

/**
 * If the server response was invalid.
 * `{{statusCode}}` will be replaced with the servers status code.
 */
dictResponseError: "Server responded with {{statusCode}} code.",

/**
 * If `addRemoveLinks` is true, the text to be used for the cancel upload link.
 */
dictCancelUpload: "Cancel upload",

/**
 * The text that is displayed if an upload was manually canceled
 */
dictUploadCanceled: "Upload canceled.",

/**
 * If `addRemoveLinks` is true, the text to be used for confirmation when cancelling upload.
 */
dictCancelUploadConfirmation: "Are you sure you want to cancel this upload?",

/**
 * If `addRemoveLinks` is true, the text to be used to remove a file.
 */
dictRemoveFile: "Remove file",

/**
 * If this is not null, then the user will be prompted before removing a file.
 */
dictRemoveFileConfirmation: null,

/**
 * Displayed if `maxFiles` is st and exceeded.
 * The string `{{maxFiles}}` will be replaced by the configuration value.
 */
dictMaxFilesExceeded: "You can not upload any more files.",

/**
 * Allows you to translate the different units. Starting with `tb` for terabytes and going down to
 * `b` for bytes.
 */
dictFileSizeUnits: {
  tb: "TB",
  gb: "GB",
  mb: "MB",
  kb: "KB",
  b: "b"
},

/**
 * Called when dropzone initialized
 * You can add event listeners here
 */
init: function init() {},

/**
 * Can be an **object** of additional parameters to transfer to the server, **or** a `Function`
 * that gets invoked with the `files`, `xhr` and, if it's a chunked upload, `chunk` arguments. In case
 * of a function, this needs to return a <a href="https://www.jqueryscript.net/tags.php?/map/">map</a>.
 *
 * The default implementation does nothing for normal uploads, but adds relevant information for
 * chunked uploads.
 *
 * This is the same as adding hidden input fields in the form element.
 */
params: function params(files, xhr, chunk) {
  if (chunk) {
    return {
      dzuuid: chunk.file.upload.uuid,
      dzchunkindex: chunk.index,
      dztotalfilesize: chunk.file.size,
      dzchunksize: this.options.chunkSize,
      dztotalchunkcount: chunk.file.upload.totalChunkCount,
      dzchunkbyteoffset: chunk.index * this.options.chunkSize
    };
  }
},

/**
 * A function that gets a [file](https://developer.mozilla.org/en-US/docs/DOM/File)
 * and a `done` function as parameters.
 *
 * If the done function is invoked without arguments, the file is "accepted" and will
 * be processed. If you pass an error message, the file is rejected, and the error
 * message will be displayed.
 * This function will not be called if the file is too big or doesn't match the mime types.
 */
accept: function accept(file, done) {
  return done();
},

/**
 * The callback that will be invoked when all chunks have been uploaded for a file.
 * It gets the file for which the chunks have been uploaded as the first parameter,
 * and the `done` function as second. `done()` needs to be invoked when everything
 * needed to finish the upload process is done.
 */
chunksUploaded: function chunksUploaded(file, done) {
  done();
},

/**
 * Gets called when the browser is not supported.
 * The default implementation shows the fallback input field and adds
 * a text.
 */
fallback: function fallback() {
  // This code should pass in IE7... :(
  var messageElement;
  this.element.className = "".concat(this.element.className, " dz-browser-not-supported");
  var _iteratorNormalCompletion2 = true;
  var _didIteratorError2 = false;
  var _iteratorError2 = undefined;

  try {
    for (var _iterator2 = this.element.getElementsByTagName("div")[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
      var child = _step2.value;

      if (/(^| )dz-message($| )/.test(child.className)) {
        messageElement = child;
        child.className = "dz-message"; // Removes the 'dz-default' class

        break;
      }
    }
  } catch (err) {
    _didIteratorError2 = true;
    _iteratorError2 = err;
  } finally {
    try {
      if (!_iteratorNormalCompletion2 && _iterator2["return"] != null) {
        _iterator2["return"]();
      }
    } finally {
      if (_didIteratorError2) {
        throw _iteratorError2;
      }
    }
  }

  if (!messageElement) {
    messageElement = Dropzone.createElement("<div class=\"dz-message\"><span></span></div>");
    this.element.appendChild(messageElement);
  }

  var span = messageElement.getElementsByTagName("span")[0];

  if (span) {
    if (span.textContent != null) {
      span.textContent = this.options.dictFallbackMessage;
    } else if (span.innerText != null) {
      span.innerText = this.options.dictFallbackMessage;
    }
  }

  return this.element.appendChild(this.getFallbackForm());
},

/**
 * Gets called to calculate the thumbnail dimensions.
 *
 * It gets `file`, `width` and `height` (both may be `null`) as parameters and must return an object containing:
 *
 *  - `srcWidth` & `srcHeight` (required)
 *  - `trgWidth` & `trgHeight` (required)
 *  - `srcX` & `srcY` (optional, default `0`)
 *  - `trgX` & `trgY` (optional, default `0`)
 *
 * Those values are going to be used by `ctx.drawImage()`.
 */
resize: function resize(file, width, height, resizeMethod) {
  var info = {
    srcX: 0,
    srcY: 0,
    srcWidth: file.width,
    srcHeight: file.height
  };
  var srcRatio = file.width / file.height; // Automatically calculate dimensions if not specified

  if (width == null && height == null) {
    width = info.srcWidth;
    height = info.srcHeight;
  } else if (width == null) {
    width = height * srcRatio;
  } else if (height == null) {
    height = width / srcRatio;
  } // Make sure images aren't upscaled


  width = Math.min(width, info.srcWidth);
  height = Math.min(height, info.srcHeight);
  var trgRatio = width / height;

  if (info.srcWidth > width || info.srcHeight > height) {
    // Image is bigger and needs rescaling
    if (resizeMethod === 'crop') {
      if (srcRatio > trgRatio) {
        info.srcHeight = file.height;
        info.srcWidth = info.srcHeight * trgRatio;
      } else {
        info.srcWidth = file.width;
        info.srcHeight = info.srcWidth / trgRatio;
      }
    } else if (resizeMethod === 'contain') {
      // Method 'contain'
      if (srcRatio > trgRatio) {
        height = width / srcRatio;
      } else {
        width = height * srcRatio;
      }
    } else {
      throw new Error("Unknown resizeMethod '".concat(resizeMethod, "'"));
    }
  }

  info.srcX = (file.width - info.srcWidth) / 2;
  info.srcY = (file.height - info.srcHeight) / 2;
  info.trgWidth = width;
  info.trgHeight = height;
  return info;
},

/**
 * Can be used to transform the file (for example, resize an image if necessary).
 *
 * The default implementation uses `resizeWidth` and `resizeHeight` (if provided) and resizes
 * images according to those dimensions.
 *
 * Gets the `file` as the first parameter, and a `done()` function as the second, that needs
 * to be invoked with the file when the transformation is done.
 */
transformFile: function transformFile(file, done) {
  if ((this.options.resizeWidth || this.options.resizeHeight) && file.type.match(/image.*/)) {
    return this.resizeImage(file, this.options.resizeWidth, this.options.resizeHeight, this.options.resizeMethod, done);
  } else {
    return done(file);
  }
},

/**
 * A string that contains the template used for each dropped
 * file. Change it to fulfill your needs but make sure to properly
 * provide all elements.
 *
 * If you want to use an actual HTML element instead of providing a String
 * as a config option, you could create a div with the id `tpl`,
 * put the template inside it and provide the element like this:
 *
 *     document
 *       .querySelector('#tpl')
 *       .innerHTML
 *
 */
previewTemplate: "<div class=\"dz-preview dz-file-preview\">\n  <div class=\"dz-image\"><img data-dz-thumbnail /></div>\n  <div class=\"dz-details\">\n    <div class=\"dz-size\"><span data-dz-size></span></div>\n    <div class=\"dz-filename\"><span data-dz-name></span></div>\n  </div>\n  <div class=\"dz-progress\"><span class=\"dz-upload\" data-dz-uploadprogress></span></div>\n  <div class=\"dz-error-message\"><span data-dz-errormessage></span></div>\n  <div class=\"dz-success-mark\">\n    <svg width=\"54px\" height=\"54px\" viewBox=\"0 0 54 54\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n      <title>Check</title>\n      <g stroke=\"none\" stroke-width=\"1\" fill=\"none\" fill-rule=\"evenodd\">\n        <path d=\"M23.5,31.8431458 L17.5852419,25.9283877 C16.0248253,24.3679711 13.4910294,24.366835 11.9289322,25.9289322 C10.3700136,27.4878508 10.3665912,30.0234455 11.9283877,31.5852419 L20.4147581,40.0716123 C20.5133999,40.1702541 20.6159315,40.2626649 20.7218615,40.3488435 C22.2835669,41.8725651 24.794234,41.8626202 26.3461564,40.3106978 L43.3106978,23.3461564 C44.8771021,21.7797521 44.8758057,19.2483887 43.3137085,17.6862915 C41.7547899,16.1273729 39.2176035,16.1255422 37.6538436,17.6893022 L23.5,31.8431458 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z\" stroke-opacity=\"0.198794158\" stroke=\"#747474\" fill-opacity=\"0.816519475\" fill=\"#FFFFFF\"></path>\n      </g>\n    </svg>\n  </div>\n  <div class=\"dz-error-mark\">\n    <svg width=\"54px\" height=\"54px\" viewBox=\"0 0 54 54\" version=\"1.1\" xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\">\n      <title>Error</title>\n      <g stroke=\"none\" stroke-width=\"1\" fill=\"none\" fill-rule=\"evenodd\">\n        <g stroke=\"#747474\" stroke-opacity=\"0.198794158\" fill=\"#FFFFFF\" fill-opacity=\"0.816519475\">\n          <path d=\"M32.6568542,29 L38.3106978,23.3461564 C39.8771021,21.7797521 39.8758057,19.2483887 38.3137085,17.6862915 C36.7547899,16.1273729 34.2176035,16.1255422 32.6538436,17.6893022 L27,23.3431458 L21.3461564,17.6893022 C19.7823965,16.1255422 17.2452101,16.1273729 15.6862915,17.6862915 C14.1241943,19.2483887 14.1228979,21.7797521 15.6893022,23.3461564 L21.3431458,29 L15.6893022,34.6538436 C14.1228979,36.2202479 14.1241943,38.7516113 15.6862915,40.3137085 C17.2452101,41.8726271 19.7823965,41.8744578 21.3461564,40.3106978 L27,34.6568542 L32.6538436,40.3106978 C34.2176035,41.8744578 36.7547899,41.8726271 38.3137085,40.3137085 C39.8758057,38.7516113 39.8771021,36.2202479 38.3106978,34.6538436 L32.6568542,29 Z M27,53 C41.3594035,53 53,41.3594035 53,27 C53,12.6405965 41.3594035,1 27,1 C12.6405965,1 1,12.6405965 1,27 C1,41.3594035 12.6405965,53 27,53 Z\"></path>\n        </g>\n      </g>\n    </svg>\n  </div>\n</div>",Copy

 

Dropzone API 메서드

javascript
// remove a file
myUploader.removeFile(file);

// enable/disable the file uploader
myUploader.enable();
myUploader.disable();

// get files
myUploader.getAcceptedFiles();
myUploader.getRejectedFiles();
myUploader.getQueuedFiles();
myUploader.getUploadingFiles();Copy

 

Dropzone 이벤트 핸들러

javascript
myUploader.on("drop", function(e) {
  // do something
});

myUploader.on("dragstart", function(e) {
  // do something
});

myUploader.on("dragend", function(e) {
  // do something
});

myUploader.on("dragenter", function(e) {
  // do something
});

myUploader.on("dragover", function(e) {
  // do something
});

myUploader.on("dragleave", function(e) {
  // do something
});

myUploader.on("addedfile", function(file) {
  // do something
});

myUploader.on("processing", function(file) {
  // do something
});

myUploader.on("removedfile", function(file) {
  // do something
});

myUploader.on("thumbnail", function(file, dataURL) {
  // do something
});

myUploader.on("error", function(file) {
  // do something
});

myUploader.on("uploadprogress", function(file, progress, bytesSent) {
  // do something
});

myUploader.on("sending", function(file, formData) {
  // do something
});

myUploader.on("success", function(file) {
  // do something
});

myUploader.on("complete", function(file) {
  // do something
});

myUploader.on("canceled", function(file) {
  // do something
});

myUploader.on("maxfilesreached", function(file) {
  // do something
});

myUploader.on("maxfilesexceeded", function(file) {
  // do something
});

myUploader.on("processingmultiple", function(fileList) {
  // do something
});

myUploader.on("sendingmultiple", function(fileList) {
  // do something
});

myUploader.on("successmultiple", function(fileList) {
  // do something
});

myUploader.on("completemultiple", function(fileList) {
  // do something
});

myUploader.on("canceledmultiple", function(fileList) {
  // do something
});

myUploader.on("reset", function(e) {
  // do something
});

myUploader.on("queuecomplete", function(e) {
  // do something
});

myUploader.on("totaluploadprogress", function(uploadProgress, totalBytes, totalBytesSent) {
  // do something
});Copy

출처: https://inpa.tistory.com/entry/Dropzone-📚-이미지-파일-업로드-드래그-앤-드롭-라이브러리-사용법 [Inpa Dev 👨‍💻:티스토리]

0
0
이 글을 페이스북으로 퍼가기 이 글을 트위터로 퍼가기 이 글을 카카오스토리로 퍼가기 이 글을 밴드로 퍼가기

HTML/CSS/기타

번호 제목 글쓴이 날짜 조회수
42 datepicker 사용하여 공휴일 직접 지정하기 관리자 06-11 65
41 Dropzone - 이미지 & 파일 업로드 (드래그 앤 드롭) 라이브러리 관리자 03-06 279
40 JSPDF 사용법(Javascript pdf) 관리자 03-04 301
39 FullCalendar(풀캘린더) 어거지 사용법 관리자 01-25 455
38 JQUERY - id가 여러개인데 한번에 찾고 싶을때! ${} 관리자 12-28 317
37 [CSS] 가로 스크롤 구현하기 관리자 12-27 412
36 JCROP을 이용한 업로드한 크롭( CROP ) 하기 관리자 12-27 362
35 제이쿼리 - 모달 다이아로그 및 여러 알림창들 관리자 12-21 183
34 Javascript/jQuery 이미지 회전 돋보기 관리자 11-07 408
33 Resolving the Issue of Fakepath in JavaScript 관리자 10-26 209
32 div 및 요소 화면 중앙에 위치시키기 관리자 10-21 240
31 [Jquery] 체크박스 전체 체크 , 해제 하는 방법 관리자 10-19 235
30 display 스타일 속성 사용하여 행 숨기기/보이기 관리자 09-16 392
29 자주 사용하는 비주얼 스튜디오 코드(Visual Studio Code, VSC, vscode) 단축키 정리 관리자 09-14 564
28 div 2개 나란히 정렬하는 방법 관리자 09-09 336
27 HTML, CSS - 헤더컬럼 고정형 table 구성하기 관리자 09-06 247
26 Drag and Drop File Upload 관리자 09-03 259
25 rowspan으로 합친 table에서 룰오버 관리자 08-23 457
24 스마트에디터 입력 용량 체크 관리자 07-06 537
23 자바스크립트 정규표현식 모음 관리자 07-03 323