bootstrap fileinput上传,下载

本文介绍了一个基于fileinput.js的文件上传组件实现,包括初始化样式、上传控件、处理文件上传及后端配置等内容。涉及fileinput.js的使用、Tomcat配置文件大小限制、后端文件保存及下载功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

需引入fileinput.js和fileinput.min.css,地址:https://gitee.com/jolone/source.git

<div class="change_Pass_style" id="fileUpload">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                    <h4 class="modal-title" id="myModalLabel" th:text="${model.selectApk}">请选择apk文件</h4>
                </div>
                <div class="modal-body">
                    <input type="file" name="txt_file" id="txt_file" multiple class="file-loading" />
                </div></div>
        </div>
</div>

$(function () {
        //初始化fileinput
        var oFileInput = new FileInput();
        oFileInput.Init("txt_file", "/api/OrderApi/ImportOrder");
    });

    var cabinet_id = '';
    var FileInput = function () {
        var oFile = new Object();

        //初始化fileinput控件(第一次初始化)
        oFile.Init = function(ctrlName, uploadUrl) {
            var control = $('#' + ctrlName);

            //初始化上传控件的样式
            control.fileinput({
                language: 'en', //设置语言
                uploadUrl: 'sysUploadSoftware', //上传的地址
                allowedFileExtensions: ['jpg', 'png', 'apk'],//接收的文件后缀
                showUpload: true, //是否显示上传按钮
                showCaption: false,//是否显示标题
                browseClass: "btn btn-primary", //按钮样式
                //dropZoneEnabled: false,//是否显示拖拽区域
                //minImageWidth: 50, //图片的最小宽度
                //minImageHeight: 50,//图片的最小高度
                //maxImageWidth: 1000,//图片的最大宽度
                //maxImageHeight: 1000,//图片的最大高度
                maxFileSize: 0,//单位为kb,如果为0表示不限制文件大小
                //minFileCount: 0,
                maxFileCount: 10, //表示允许同时上传的最大文件个数
                enctype: 'multipart/form-data',
                validateInitialCount:true,
                previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
                msgFilesTooMany: "选择上传的文件数量过多",
                uploadExtraData:function(){//向后台传递参数
                    var data={
                        cabinetId:cabinet_id
                    };
                    return data;
                },
            });

            cabinet_id = '';
            //导入文件上传完成之后的事件
            $("#txt_file").on("fileuploaded", function (event, data, previewId, index) {
                $("#myModal").modal("hide");
                var data = data.response.lstOrderImport;
                if (data == undefined) {
                    toastr.error('文件格式类型不正确');
                    return;
                }
                //1.初始化表格
                var oTable = new TableInit();
                oTable.Init(data);
                $("#div_startimport").show();
            });
        }
        return oFile;
    };

文件过大时,修改Tomcat默认文件大小

package com.ys.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.MultipartConfigElement;

@Configuration
public class TomcatConfig {

    @Value("${spring.server.MaxFileSize}")
    private String MaxFileSize;
    @Value("${spring.server.MaxRequestSize}")
    private String MaxRequestSize;

    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        //  单个数据大小
        factory.setMaxFileSize(MaxFileSize); // KB,MB
        /// 总上传数据大小
        factory.setMaxRequestSize(MaxRequestSize);
        return factory.createMultipartConfig();
    }
}

application配置文件
spring.server.MaxFileSize=300MB
spring.server.MaxRequestSize=500MB

获取项目目录,后端保存

		 @PostMapping("sysUploadSoftware")
    @ResponseBody
    public JsonResult sysUploadSoftware(@RequestParam(value = "txt_file")MultipartFile multipartFile,@RequestParam(value = "cabinetId")String cabientId){
        JsonResult json = new JsonResult();
        json.setOk(false);
        try{
            String fileName = multipartFile.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            //获取跟目录
//            File path = new File(ResourceUtils.getURL("classpath:").getPath());
            File upload = new File(PagesConfig.FILE_PATH);
            if(!upload.exists()) upload.mkdirs();
            json.setOk(true);
            multipartFile.transferTo(new File(PagesConfig.FILE_PATH + fileName));
            return json;
        }catch (Exception e){
        json.setOk(false);
            return json;
        }
    }

下载后端代码

    public void sysDownloadSoftware(HttpServletResponse response, @RequestParam(value = "cabinetId") String cabientId) throws Exception {

        Software software = softwareService.selectByCabientId(cabientId);
        if (StringUtils.isNull(software)){
            return;
        }
        File file = new File(software.getUrl());
        String fileName = software.getCurrentVersion();
        if (file.exists()) {
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;fileName=" + fileName+";filename*=utf-8''"+ URLEncoder.encode(fileName,"UTF-8"));
            ///设置文件名编码格式
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file);
                bis = new BufferedInputStream(fis);
                OutputStream outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    outputStream.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值