【问题标题】:Upload file excel and read with JAX-RS 2.0 in java上传文件excel并在java中使用JAX-RS 2.0读取
【发布时间】:2020-05-13 04:37:14
【问题描述】:

我有上传文件 excel 功能,可以在带有 JAX-RS 1.1 的 Websphere server 8.5 中正常运行。但是当我使用 JAX_RS 2.0 更新到 Websphere 9.0 时,我无法使用 @FormParam 上传文件,我尝试使用 @MultiPart 替换但它只能正确读取 .csv 文件,使用 .xls 和 .xlsx 文件会创建错误的临时文件,所以 Apache Poi 的 HSSFWorkbook 无法正常读取文件的输入流。 这是我的代码:

控制器:

@POST
    @Path("class/import")
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Produces(MediaType.APPLICATION_JSON)
    @RolesAllowed(Role.TRAINING_ADMIN)
    public Response importClass(@FormParam("file") File file) {

        InputStream is = new FileInputStream(file);
        HSSFWorkbook workbook = new HSSFWorkbook(is);
        if (checkTokenAndRole(new int[] {1, 11}).getStatus() != Response.Status.OK.getStatusCode()) {           
            return LoginError(checkToken().getStatus());                
        } else {
            String token = request.getHeader(HttpHeaders.AUTHORIZATION);
            String fileExtension = request.getHeader("FileExtension");
            return ClassService.getInstance().importClass(file, fileExtension,
                    token);
        }
    }

HTML 和 Js 文件:

<form data-bind="submit: cancel">
    <div class="modal-dialog dialog-class">
        <div class="modal-content dialog-class">
            <div class="modal-header layout-dialog-header">
                <div class="layout-float-left dialog-close-icon">
                    <span class="glyphicon doc-icon-close-nav" data-bind="click: cancel"></span>
                </div>
                <div>
                    <h5 data-bind="text: title" data-i18n="modules.class.uploadSchedule"></h5>
                </div>
            </div>

            <div class=" docs-margin-top-s">
                    <div>
                        <div class="form-group marginBot35">
                            <div class="class-browse">
                                <div class="col-md-12">
                                    <div>
                                        <label class="label-md search-class-header" for="">
                                        <span class="search-class-header" data-i18n="modules.class.uploadClasslist" data-bind="text: listClass"></span>
                                        </label>
                                    </div>
                                    <div id="" class="col-md-8 control-upload no-padding-left">
                                        <input readonly="true" tabindex="3" class="col-md-12" id='uploadFile' type="text" name=""  style="min-height: 40px" data-bind="value: name, attr: {'title': name()}"/>
                                    </div>
                                    <div clas="col-md-4">
                                        <label for="input-file-upload" tabindex="3" class="pull-right btn btn-secondary-aia btn-cancel font-size20" data-dismiss="modal"
                                        data-i18n="buttons.buttonBrowse" >Browse
                                        </label>
                                    </div>
                                </div>
                                <div class="class-center-align">
                                    <label class="label-md search-class-header " for="">
                                        <span class="search-class-header" data-i18n="modules.class.downloadThe">Download the</span>
<!--                                         <a class="class-highlight" tabindex="3" data-i18n="modules.class.trainingSchedule" data-bind="attr: {href: template}, text: textTemplate" download>Training Schedule Template</a> -->
                                            <a class="class-highlight" tabindex="3" data-i18n="modules.class.trainingSchedule" data-bind="click: $root.download, text: textTemplate" >Training Schedule Template</a>
                                    </label>
                                </div>
                            </div>
                        </div>
                    </div>
            </div>
            <div class="col-md-12 footer-class" style="padding-bottom:40px">
                <button tabindex="3" type="button" class="btn btn-secondary-aia btn-cancel font-size20" data-dismiss="modal" data-i18n="buttons.buttonCancel" data-bind="click: cancel"></button>
                <button tabindex="3" type="submit" class="btn btn-primary-aia btn-save font-size20 " style=" cursor: pointer; word-spacing: normal !important" data-bind="click: upload, disable: !readyUpload(),text: buttonUpload" data-dismiss="modal" data-i18n="buttons.buttonUploadSchedule"></button>
            </div>
        </div>
    </div>
</form>


<form id="form-input-file-upload" action="" method="post" enctype="multipart/form-data" style="display:none">
    <input id="input-file-upload" type="file" style="" name="file" size="45" accept=".xls,.xlsx" style="display:none" data-bind="attr: {accept: acceptedFiles},event: {change: addFile}" >
</form>

define([
    'durandal/app',
    'durandal/events',
    'plugins/dialog',
    'plugins/http',
    'knockout',
    'jquery',
    'config',
    'services/utils',
    'i18next',
    'services/document'
], function (app, Events, dialog, http, ko, $, Config, Utils, i18next, DocumentService) {
    'use strict';

            return function UploadBulkSchedule(mode) {
        var self = this;
        Events.includeIn(self);
        if(mode === 1){
            self.title = ko.observable( i18next.t("modules.bulkAttendee.title") ?  i18next.t("modules.bulkAttendee.title") :  "");
            self.listClass = ko.observable( i18next.t("modules.bulkAttendee.listClass") ?  i18next.t("modules.bulkAttendee.listClass") : "");
            self.textTemplate = ko.observable( i18next.t("modules.bulkAttendee.template") ?  i18next.t("modules.bulkAttendee.template") : "");
            self.buttonUpload = ko.observable( i18next.t("modules.bulkAttendee.buttonUpload") ?  i18next.t("modules.bulkAttendee.buttonUpload") : "");
        }else{
            self.title = ko.observable( i18next.t("modules.class.uploadSchedule") ?  i18next.t("modules.class.uploadSchedule") :  "");
            self.listClass = ko.observable( i18next.t("modules.class.uploadClasslist") ?  i18next.t("modules.class.uploadClasslist") : "");
            self.textTemplate = ko.observable( i18next.t("modules.class.trainingSchedule") ?  i18next.t("modules.class.trainingSchedule") :  "");
            self.buttonUpload = ko.observable( i18next.t("buttons.buttonUploadSchedule") ?  i18next.t("buttons.buttonUploadSchedule") : "");
        }
        self.name = ko.observable();


        var acceptedFileArr = [
                            'application/vnd.ms-excel',
                            'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                            'application/csv',
                            '.xls','.xlsx', '.csv'];
        var acceptedExtension = ['xls', 'xlsx', 'csv'];
        self.mode = mode;
        self.acceptedFiles = ko.observable(acceptedFileArr.join(','));
        self.readyUpload = ko.computed(function(){
            return self.name() ? true : false;
        });
        var maxSize = 5242880;

        self.template = (self.mode === 1) ? Config.getBackendBaseUrl('/temp/excel/AttendanceImportTemplate/AttendeeListTemplate.xls') :Config.getBackendBaseUrl('/temp/excel/ClassImportTemplate/ClassImportTemplate.zip');
        self.templateCSV = Config.getBackendBaseUrl('/temp/excel/ClassImportTemplate/ClassImportTemplate.csv');
        var filesArray = [];


        self.cancel = function(){
            dialog.close(self); 
        };


        self.active = function(){

        };

        self.upload = function(data, e){
            e.preventDefault();

            app.showLoading();
            var inputTag = $('#form-input-file-upload :input')[0];
            var fileName = $(inputTag).val().replace(/^.*[\\\/]/, '');

            var extension = fileName.split('.').pop();

             var headers = {
                        FileExtension: extension,
                        FileName: encodeURIComponent(fileName),
                        'Authorization':  app.user().get('token'),
                        'isCourseImage': 0
                    };
                    if (self.mode === 1) {

                        self.trigger('uploadSuccess', [ $('#form-input-file-upload :input')[0] ]);

                    } else {
                        Utils
                                .uploadFile(
                                        'class/import',
                                        new FormData(
                                                $('#form-input-file-upload')[0]),
                                        headers)
                                .then(
                                        function() {
                app.hideLoading();
                                        },
                                        function(response) {
                                            var title = i18next
                                                    .t('modules.class.errorTitle');
                var options = [{
                                                text : i18next
                                                        .t('buttons.buttonOk'),
                    value: Config.Events.DialogMessage.OK
                }];
                if(response.status === 200){
                    app.hideLoading();
                } else if(response.status === 500){
                                                var errorMessage = Utils
                                                        .getErrorMessage(response);
                    var errorCode = '';
                    var developerMessage = '';
                    try{
                                                    errorCode = JSON
                                                            .parse(response.responseText).errorCode;
                                                    developerMessage = JSON
                                                            .parse(response.responseText).message;
                    } catch(e){
                    }

                                                if (errorCode === 1007
                                                        && developerMessage) {
                                                    var messageContent = '<br></br><b>'
                                                            + i18next
                                                                    .t(
                                                                            'message.error.importClassSuccess')
                                                                    .format(
                                                                            developerMessage)
                                                            + '</b><br></br>';
                                                    title = i18next
                                                            .t('message.error.importSuccess');
                                                    app
                                                            .showMessageConfirmTitle(
                                                                    messageContent,
                                                                    title,
                                                                    options,
                                                                    false,
                                                                    {
                                                                        class : 'success-class'
                                                                    })
                                                            .then(
                                                                    function() {
                                                                        self
                                                                                .trigger('uploadSuccess');
                                                                        dialog
                                                                                .close(self);
                        });
                    } else if(errorMessage){
                                                    app.showMessageError(
                                                            errorMessage,
                                                            title, options,
                                                            false, null);
                    }
                } else if(response.status === 0) {
                                                var errorMessage = i18next
                                                        .t('message.error.notSaveClassList');
                                                app.showMessageError(
                                                        errorMessage, title,
                                                        options, false, null);

                }
                app.hideLoading();
            });
                    }
        };

        self.browse = function(){
            filesArray = [];
            document.getElementById("uploadFile").click();
        };

        self.addFile = function(data, event){
            var inputFile = document.getElementById("input-file-upload");
            var path = inputFile.value.toString();

            var uploadFile = event.currentTarget;

            var file = uploadFile.files[0];
            var fsize = file.size;

            var name, extension;
            name =  path.replace(/^.*[\\\/]/, '');
            extension = name.split('.').pop();        


            if( fsize > maxSize){
                self.name('');
                $('#input-file-upload').replaceWith($('#input-file-upload').clone(true));
                showUploadMessageWithData(file);
                $('#input-file-upload')[0].value = '';
            } else if(acceptedExtension.indexOf(extension.toLowerCase()) < 0){
                self.name('');
                $('#input-file-upload').replaceWith($('#input-file-upload').clone(true));  
                var messageContent = '<br/><b>'+i18next.t('modules.class.wrongFileExtension')+' </b><br/>';
                var options = [{
                    text: i18next.t('buttons.buttonClose'),
                    value: Config.Constants.MessageBox.DialogResult.BUTTON_INDEX_0
                }];
                var title = i18next.t('modules.class.errorTitle');
                app.showMessageError(messageContent, title, options, false, null);
                $('#input-file-upload')[0].value = '';
            } else {
                self.name(name);
            }
        };

        function showUploadMessageWithData (file) {
            var messageContent = '<p style="white-space: pre-wrap">'+i18next.t('modules.course.editPage.fileName')+': ' + file.name + '</p>';
            messageContent += '</br><p><b>'+i18next.t('modules.course.editPage.warnUploadFile')+' </b></p>';            messageContent += '<p><b>'+i18next.t('modules.course.editPage.requireUploadFile')+ ' </b></p>';
            var options = [{
                text: i18next.t('buttons.buttonOk'),
                value: Config.Constants.MessageBox.DialogResult.BUTTON_INDEX_0
            }];
            var title = i18next.t('modules.class.errorTitle');
            return app.showMessageError(messageContent, title, options, false, {class: 'confirm-class'}).then(function () {
            });
        }

      //download Material
        self.download = function(fileDownload){
            app.showLoading();
            DocumentService.downloadTemplate(fileDownload.template).then(function (response) {
                app.hideLoading();
                var extension = fileDownload.template.split('.').pop();
                var ctType = '';
                switch(extension) {
                case 'jpg':
                case 'jpeg':
                    ctType = 'image/jpeg';
                    break;
                case 'png':
                    ctType = 'image/png';
                    break;
                case 'doc':
                    ctType = 'application/msword';
                    break;
                case 'docx':
                    ctType = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document';
                    break;
                case 'xls':
                    ctType = 'application/vnd.ms-excel';
                    break;
                case 'xlsx':
                    ctType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
                    break;
                case 'ppt':
                    ctType = 'application/vnd.ms-powerpoint';
                    break;
                case 'pptx':
                    ctType = 'application/vnd.openxmlformats-officedocument.presentationml.presentation';
                    break;
                case 'pdf':
                    ctType = 'application/pdf';
                    break;

                default:
                    break;
            }                
                var byteArray = new Uint8Array(response.data);
                var a = window.document.createElement('a');
                a.setAttribute("id", "tmpHref");
                a.href = window.URL.createObjectURL(new Blob([byteArray], { type: ctType }));
                a.download = fileDownload.template.split("/")[fileDownload.template.split("/").length - 1];
                // Append anchor to body.
                document.body.appendChild(a);
                a.click();
                // Remove anchor from body
                document.body.removeChild(a);
            }, function (response) {
                app.hideLoading();
                Utils.downloadMaterial(response);
            });
        };

    };
});

谁能帮我解决? 谢谢。

【问题讨论】:

    标签: java excel jax-rs


    【解决方案1】:

    我有解决办法。我将使用 IMultipartBody 改为使用 @FormParam,将 ImultipartBody 更改为字节数组并使用它而不是文件。

    【讨论】:

      猜你喜欢
      • 2014-11-06
      • 1970-01-01
      • 2014-09-11
      • 1970-01-01
      • 1970-01-01
      • 2015-11-01
      • 1970-01-01
      • 2018-06-10
      • 1970-01-01
      相关资源
      最近更新 更多