若依框架--上傳下載(基於spring boot + bootstrap)

最近基於若依框架做了一套後臺管理系統,使用到上傳和下載功能,一起學習和分享下;

上傳功能

前端:

引入樣式:

    <th:block th:include="include :: bootstrap-fileinput-css"/>

然後div樣式:

        <div class="row">
            <div class="col-sm-12">
                <div class="form-group">
                    <div class="file-loading">
                        <input id="input-folder-3" type="file" name="file" multiple>
                    </div>
                </div>
            </div>
        </div>

引入:

<th:block th:include="include :: footer"/>
<th:block th:include="include :: bootstrap-fileinput-js"/>
<th:block th:include="include :: datetimepicker-js"/>

必要時前端可以調試修改js,因爲這個組件本身上傳後有,上傳、移除、閱覽功能,若需要單個文件下載功能的可以自己調試。

然後是javascript:

<script type="text/javascript">
    var prefix = ctx + "invoice/saleInvoice";

    $("#form-info-edit").validate({
        focusCleanup: true
    });

    function submitHandler() {
        if ($.validate.form()) {
            $.operate.save(prefix + "/applyOpenInvoice", $('#form-info-edit').serialize());
        }
    }

    $(document).ready(function () {
        $("#input-folder-3").fileinput({
            uploadUrl: prefix + "/addFile",
            uploadExtraData: function () {//向後臺傳遞參數,需要根據id更新對應信息
                var data = {
                    id: $("#id").val(),
                };
                return data;
            },
            // otherActionButtons: '<button type="button" class="kv-file-down btn btn-sm btn-default" {dataKey}  onclick="downloadFile()" title="下載附件"><i class="fa fa-cloud-download"></i></button>',

            uploadAsync: false,//false 同步上傳,後臺用數組接收,true 異步上傳,每次上傳一個file,會調用多次接口
            showRemove: true,//顯示移除按鈕
            showPreview: true,//是否顯示預覽
            showCaption: true,//是否顯示文字描述
            maxFileCount: 10,//最大可選文件數
            // removeFromPreviewOnError:true, //當選擇的文件不符合規則時,例如不是指定後綴文件、大小超出配置等,選擇的文件不會出現在預覽框中,只會顯示錯誤信息
            // enctype: 'multipart/form-data',
            // uploadExtraData: function () {//向後臺傳遞參數
            //     var data = {
            //         apkName: $("#apkName").val(),
            //         versionNum: $("#versionNum").val(),
            //         description: $("#description").val()
            //     };
            //     return data;
            // },
            hideThumbnailContent: true // hide image, pdf, text or other content in the thumbnail preview

        });
    });
</script>

選中文件打開後,會出現移除和上傳按鈕,單個文件上也有單獨移除、單獨上傳、閱覽按鈕,點擊上傳會調用到後臺處理,

上傳的後臺邏輯:

直接看代碼:

@PostMapping("/addFile")
    @ResponseBody
    public AjaxResult insert(HttpServletRequest request, HttpServletResponse response, @RequestParam("file") MultipartFile[] file) throws Exception {

        String id = request.getParameter("id");//當需對
        logger.info("獲取選中數據主鍵:{}", id);

        if (file != null && file.length > 0) {
            List<String> fileName = new ArrayList<String>();
            // 上傳文件路徑
            String filePath = RuoYiConfig.getUploadPath();
          
           
            try {
                for (int i = 0; i < file.length; i++) {
                    if (!file[i].isEmpty()) {
                        //上傳文件
                        fileName.add(uploadImage(request, filePath, file[i], false));
                    }
                }
                //上傳成功
                if (fileName != null && fileName.size() > 0) {
                    return AjaxResult.success("上傳成功!");
                } else {
                    return AjaxResult.error("上傳失敗!文件格式錯誤!");
                }
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("上傳出現異常!");
            }
        } else {
            return AjaxResult.error("未檢測到文件!");
        }
    }
/**
     * 上傳文件
     * 原名稱
     *
     * @param request      請求
     * @param path_deposit 存放位置(路徑)
     * @param file         文件
     * @param isRandomName 是否隨機名稱
     * @return 完整文件路徑
     */
    public String uploadImage(HttpServletRequest request, String path_deposit, MultipartFile file, boolean isRandomName) {
        try {
            if (file != null) {
                String origName = file.getOriginalFilename();// 文件原名稱
                System.out.println("上傳的文件原名稱:" + origName);
                //路徑+文件名稱
                String fileSrc = "";
                //是否隨機名稱
                if (isRandomName) {
                    origName = DateUtil.today() + UUID.randomUUID().toString() + origName.substring(origName.lastIndexOf("."));
                }
                // 上傳並返回新文件名稱
                String fileNameNew = FileUploadUtils.upload(path_deposit, file);
                logger.info("新文件名稱:{}", fileNameNew);
                //判斷是否存在目錄
//                        File targetFile = new File(path, origName);
//                        if (!targetFile.exists()) {
//                            targetFile.mkdirs();//創建目錄
//                        }
//                        //上傳
//                        file.transferTo(targetFile);
                //完整路徑
                fileSrc = request.getContextPath() + path_deposit + origName;
                logger.info("圖片上傳路徑:{}", fileSrc);

                
                return fileSrc;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

這段代碼方法 FileUploadUtils.upload主要執行的是  file.transferTo(targetFile),把文件格式校驗,文件名稱長度校驗

,上傳路徑校驗 什麼的抽出來了。

下載功能:

前端代碼:

後臺附件信息表返回list多筆附件信息,前端需要foreach處理(也可以用什麼js動態綁定,不會,所以。。。。)

 <div class="row" >
            <div class="col-sm-6" ><span style="color: red; ">點擊下載附件</span>
                <div th:each="invoiceFileInfo: ${invoiceFileInfoList}">
                    <input name="fileName" th:value="${invoiceFileInfo.fileName}" class="form-control"
                           type="text" readonly onclick="downloadFile(this.value)"><br/>
                    <!--<i class="fa fa-download" aria-hidden="true" title="下載"-->
                    <!--onclick="downloadFile()"></i>-->
                </div>
            </div>
        </div>
 function downloadFile(fileName) {
        var fileCode = document.getElementById("fileCode").value;//附件編號
        window.location.href = prefix + "/downloadFile/" + fileName + "/" + fileCode;
    }

後臺代碼:

**
     * 文件下載
     *
     * @param fileName,fileCode
     * @param response
     * @param request
     * @throws Exception
     */
    @GetMapping("/downloadFile/{fileName}/{fileCode}")
    public void downloadFile(@PathVariable("fileName") String fileName, @PathVariable("fileCode") String fileCode, HttpServletResponse response,
                             HttpServletRequest request) throws Exception {

        InvoiceFileInfo invoiceFile = invoiceFileInfoService.selectInvoiceFileInfoByCodeAndName(fileCode, fileName);

        String filePath = invoiceFile.getFilePath();
        String realFileName = invoiceFile.getFileName() + filePath.substring(filePath.indexOf("."));
//        String path = RuoYiConfig.getUploadPath() + invoiceFile.getFilePath();
        String path = invoiceFile.getFilePath();
        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, realFileName));
        FileUtils.writeBytes(path, response.getOutputStream());
    }

 

學習主要參考若依官網文檔,大差不差,僅供參考。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章