Can someone explain how to implement the jQuery File Upload plugin?

前端 未结 10 528
一向
一向 2020-12-02 04:44

EDIT (Oct 2019):

6 years later and jQuery File Upload is clearly still driving folks insane. If you\'re finding little solace in the answers here, try a se
相关标签:
10条回答
  • 2020-12-02 04:54

    Hi try bellow link it is very easy. I've been stuck for long time and it solve my issue in few minutes. http://simpleupload.michaelcbrook.com/#examples

    0 讨论(0)
  • 2020-12-02 04:54

    For the UI plugin, with jsp page and Spring MVC..

    Sample html. Needs to be within a form element with an id attribute of fileupload

        <!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
    <div class="fileupload-buttonbar">
        <div>
            <!-- The fileinput-button span is used to style the file input field as button -->
            <span class="btn btn-success fileinput-button">
                <i class="glyphicon glyphicon-plus"></i>
                <span>Add files</span>
                <input id="fileuploadInput" type="file" name="files[]" multiple>
            </span>
            <%-- https://stackoverflow.com/questions/925334/how-is-the-default-submit-button-on-an-html-form-determined --%>
            <button type="button" class="btn btn-primary start">
                <i class="glyphicon glyphicon-upload"></i>
                <span>Start upload</span>
            </button>
            <button type="reset" class="btn btn-warning cancel">
                <i class="glyphicon glyphicon-ban-circle"></i>
                <span>Cancel upload</span>
            </button>
            <!-- The global file processing state -->
            <span class="fileupload-process"></span>
        </div>
        <!-- The global progress state -->
        <div class="fileupload-progress fade">
            <!-- The global progress bar -->
            <div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100">
                <div class="progress-bar progress-bar-success" style="width:0%;"></div>
            </div>
            <!-- The extended global progress state -->
            <div class="progress-extended">&nbsp;</div>
        </div>
    </div>
    <!-- The table listing the files available for upload/download -->
    <table role="presentation" class="table table-striped"><tbody class="files"></tbody></table>
    
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/css/jquery.fileupload.css">
    <link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/css/jquery.fileupload-ui.css">
    
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/vendor/jquery.ui.widget.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.iframe-transport.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload-process.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload-validate.js"></script>
    <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-file-upload-9.14.2/js/jquery.fileupload-ui.js"></script>
    
    <script type="text/javascript">
        $(document).ready(function () {
                var maxFileSizeBytes = ${maxFileSizeBytes};
            if (maxFileSizeBytes < 0) {
                //-1 or any negative value means no size limit
                //set to undefined
                //https://stackoverflow.com/questions/5795936/how-to-set-a-javascript-var-as-undefined
                maxFileSizeBytes = void 0;
            }
    
            //https://github.com/blueimp/jQuery-File-Upload/wiki/Options
            //https://stackoverflow.com/questions/34063348/jquery-file-upload-basic-plus-ui-and-i18n
            //https://stackoverflow.com/questions/11337897/how-to-customize-upload-download-template-of-blueimp-jquery-file-upload
            $('#fileupload').fileupload({
                url: '${pageContext.request.contextPath}/app/uploadResources.do',
                fileInput: $('#fileuploadInput'),
                acceptFileTypes: /(\.|\/)(jrxml|png|jpe?g)$/i,
                maxFileSize: maxFileSizeBytes,
                messages: {
                    acceptFileTypes: '${fileTypeNotAllowedText}',
                    maxFileSize: '${fileTooLargeMBText}'
                },
                filesContainer: $('.files'),
                uploadTemplateId: null,
                downloadTemplateId: null,
                uploadTemplate: function (o) {
                    var rows = $();
                    $.each(o.files, function (index, file) {
                        var row = $('<tr class="template-upload fade">' +
                                '<td><p class="name"></p>' +
                                '<strong class="error text-danger"></strong>' +
                                '</td>' +
                                '<td><p class="size"></p>' +
                                '<div class="progress progress-striped active" role="progressbar" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0">' +
                                '<div class="progress-bar progress-bar-success" style="width:0%;"></div></div>' +
                                '</td>' +
                                '<td>' +
                                (!index && !o.options.autoUpload ?
                                        '<button class="btn btn-primary start" disabled>' +
                                        '<i class="glyphicon glyphicon-upload"></i> ' +
                                        '<span>${startText}</span>' +
                                        '</button>' : '') +
                                (!index ? '<button class="btn btn-warning cancel">' +
                                        '<i class="glyphicon glyphicon-ban-circle"></i> ' +
                                        '<span>${cancelText}</span>' +
                                        '</button>' : '') +
                                '</td>' +
                                '</tr>');
                        row.find('.name').text(file.name);
                        row.find('.size').text(o.formatFileSize(file.size));
                        if (file.error) {
                            row.find('.error').text(file.error);
                        }
                        rows = rows.add(row);
                    });
                    return rows;
                },
                downloadTemplate: function (o) {
                    var rows = $();
                    $.each(o.files, function (index, file) {
                        var row = $('<tr class="template-download fade">' +
                                '<td><p class="name"></p>' +
                                (file.error ? '<strong class="error text-danger"></strong>' : '') +
                                '</td>' +
                                '<td><span class="size"></span></td>' +
                                '<td>' +
                                (file.deleteUrl ? '<button class="btn btn-danger delete">' +
                                        '<i class="glyphicon glyphicon-trash"></i> ' +
                                        '<span>${deleteText}</span>' +
                                        '</button>' : '') +
                                '<button class="btn btn-warning cancel">' +
                                '<i class="glyphicon glyphicon-ban-circle"></i> ' +
                                '<span>${clearText}</span>' +
                                '</button>' +
                                '</td>' +
                                '</tr>');
                        row.find('.name').text(file.name);
                        row.find('.size').text(o.formatFileSize(file.size));
                        if (file.error) {
                            row.find('.error').text(file.error);
                        }
                        if (file.deleteUrl) {
                            row.find('button.delete')
                                    .attr('data-type', file.deleteType)
                                    .attr('data-url', file.deleteUrl);
                        }
                        rows = rows.add(row);
                    });
                    return rows;
                }
            });
    
        });
    </script>
    

    Sample upload and delete request handlers

        @PostMapping("/app/uploadResources")
    public @ResponseBody
    Map<String, List<FileUploadResponse>> uploadResources(MultipartHttpServletRequest request,
            Locale locale) {
        //https://github.com/jdmr/fileUpload/blob/master/src/main/java/org/davidmendoza/fileUpload/web/ImageController.java
        //https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#using-jquery-file-upload-ui-version-with-a-custom-server-side-upload-handler
        Map<String, List<FileUploadResponse>> response = new HashMap<>();
        List<FileUploadResponse> fileList = new ArrayList<>();
    
        String deleteUrlBase = request.getContextPath() + "/app/deleteResources.do?filename=";
    
        //http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/multipart/MultipartRequest.html
        Iterator<String> itr = request.getFileNames();
        while (itr.hasNext()) {
            String htmlParamName = itr.next();
            MultipartFile file = request.getFile(htmlParamName);
            FileUploadResponse fileDetails = new FileUploadResponse();
            String filename = file.getOriginalFilename();
            fileDetails.setName(filename);
            fileDetails.setSize(file.getSize());
            try {
                String message = saveFile(file);
                if (message != null) {
                    String errorMessage = messageSource.getMessage(message, null, locale);
                    fileDetails.setError(errorMessage);
                } else {
                    //save successful
                    String encodedFilename = URLEncoder.encode(filename, "UTF-8");
                    String deleteUrl = deleteUrlBase + encodedFilename;
                    fileDetails.setDeleteUrl(deleteUrl);
                }
            } catch (IOException ex) {
                logger.error("Error", ex);
                fileDetails.setError(ex.getMessage());
            }
    
            fileList.add(fileDetails);
        }
    
        response.put("files", fileList);
    
        return response;
    }
    
    @PostMapping("/app/deleteResources")
    public @ResponseBody
    Map<String, List<Map<String, Boolean>>> deleteResources(@RequestParam("filename") List<String> filenames) {
        Map<String, List<Map<String, Boolean>>> response = new HashMap<>();
        List<Map<String, Boolean>> fileList = new ArrayList<>();
    
        String templatesPath = Config.getTemplatesPath();
        for (String filename : filenames) {
            Map<String, Boolean> fileDetails = new HashMap<>();
    
            String cleanFilename = ArtUtils.cleanFileName(filename);
            String filePath = templatesPath + cleanFilename;
    
            File file = new File(filePath);
            boolean deleted = file.delete();
    
            if (deleted) {
                fileDetails.put(cleanFilename, true);
            } else {
                fileDetails.put(cleanFilename, false);
            }
    
            fileList.add(fileDetails);
        }
    
        response.put("files", fileList);
    
        return response;
    }
    

    Sample class for generating the required json response

        public class FileUploadResponse {
        //https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#using-jquery-file-upload-ui-version-with-a-custom-server-side-upload-handler
    
        private String name;
        private long size;
        private String error;
        private String deleteType = "POST";
        private String deleteUrl;
    
        /**
         * @return the name
         */
        public String getName() {
            return name;
        }
    
        /**
         * @param name the name to set
         */
        public void setName(String name) {
            this.name = name;
        }
    
        /**
         * @return the size
         */
        public long getSize() {
            return size;
        }
    
        /**
         * @param size the size to set
         */
        public void setSize(long size) {
            this.size = size;
        }
    
        /**
         * @return the error
         */
        public String getError() {
            return error;
        }
    
        /**
         * @param error the error to set
         */
        public void setError(String error) {
            this.error = error;
        }
    
        /**
         * @return the deleteType
         */
        public String getDeleteType() {
            return deleteType;
        }
    
        /**
         * @param deleteType the deleteType to set
         */
        public void setDeleteType(String deleteType) {
            this.deleteType = deleteType;
        }
    
        /**
         * @return the deleteUrl
         */
        public String getDeleteUrl() {
            return deleteUrl;
        }
    
        /**
         * @param deleteUrl the deleteUrl to set
         */
        public void setDeleteUrl(String deleteUrl) {
            this.deleteUrl = deleteUrl;
        }
    
    }
    

    See https://pitipata.blogspot.co.ke/2017/01/using-jquery-file-upload-ui.html

    0 讨论(0)
  • 2020-12-02 05:00

    I also struggled with this but got it working once I figured out how the paths work in UploadHandler.php: upload_dir and upload_url are about the only settings to look at to get it working. Also check your server error logs for debugging information.

    0 讨论(0)
  • 2020-12-02 05:00

    This is good Angular plugin for uploading files, and its free!

    angular file upload

    0 讨论(0)
  • 2020-12-02 05:02

    I've just spent 2 hours battling with jQuery Upload but gave up because of the amount of dependencies (I had 13 JS files included to get all the bells and whistles).

    I did a bit more searching and came across a neat project called Dropzone.js, which does not have any dependencies.

    The author has also created a bootstrap demo which was inspired by the jQuery File Upload plugin.

    I hope this saves someone else some time.

    0 讨论(0)
  • 2020-12-02 05:02

    I struggled with this plugin for a while on Rails, and then someone gemified it obsoleting all the code I had created.

    Although it looks like you're not using this in Rails, however if anyone is using it checkout this gem. The source is here --> jQueryFileUpload Rails.

    Update:

    In order to satisfy the commenter I've updated my answer. Essentially "use this gem, here is the source code" If it disappears then do it the long way.

    0 讨论(0)
提交回复
热议问题