Vue-Element UI 文件上傳與下載 項目結構 效果演示 Code

項目結構

  • 後端


  • 前端


效果演示

  • 上傳文件


  • 下載文件


Code

後端代碼

  • 跨域
/**
 * 跨域配置
 * @author Louis
 * @date Jan 12, 2019
 */
@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")  // 允許跨域訪問的路徑
        .allowedOrigins("*")    // 允許跨域訪問的源
        .allowedMethods("POST", "GET", "PUT", "OPTIONS", "DELETE")  // 允許請求方法
        .maxAge(168000) // 預檢間隔時間
        .allowedHeaders("*")  // 允許頭部設置
        .allowCredentials(true);    // 是否發送cookie
    }
}

  • 上傳文件
    /**
     * todo 文件上傳
     * @param response
     * @param file
     */
    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    public R uploadFile(HttpServletResponse response, MultipartFile file) {
        response.setContentType("text/html;charset=UTF-8");
        // 設置大小
        long maxSize = (long) (1000 * 1024 * 1024);
        Map<String, Object> result = new HashMap<String, Object>();
        String fileName = file.getOriginalFilename();
        if (file.getSize() > maxSize) {
            result.put("result", "fail");
            result.put("msg", "不能查過100MB");
            logger.warn("文件大小超過100MB");
        } else {
            try {
                Date date = new Date();
                String relativeDir = getRelativeDir(date);
                File fileDir = new File(filePath + relativeDir);
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                //新的文件名
                String newName = CommonUtil.format(date, "HHmmssSSS") +
                        Math.round(Math.random() * 8999 + 1000) +
                        fileName.substring(fileName.lastIndexOf("."));
                logger.info("文件存儲路徑:"+filePath + relativeDir + newName);
                file.transferTo(new File(filePath + relativeDir + newName));
                // 以下可以進行業務邏輯操作 插入數據庫等操作
                this.sysFileService.save(new SysFile(fileName,relativeDir + newName,file.getSize(),file.getContentType()));
                result.put("result", "success");
                result.put("data", relativeDir+newName);
                result.put("msg", "上傳成功");
                logger.info("上傳成功");
            } catch (Exception e) {
                result.put("result", "fail");
                result.put("msg", "上傳失敗");
                logger.error(e.toString());
            }
        }
        return success(result);
    }

  • 下載文件
    /**
     * todo 下載文件
     * @param response
     * @param fileId
     */
    @GetMapping("downLoadFile")
    public void downLoadFile(HttpServletResponse response, Integer fileId, HttpServletRequest request) {
        response.setHeader("Content-Type", "application/octet-stream");
        SysFile sysFile = this.sysFileService.getById(fileId);
        OutputStream out = null;
        try {
            File file = new File(filePath + sysFile.getAbsolutepath());
            response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(sysFile.getFileName(), "UTF-8"));
            FileInputStream fin = new FileInputStream(file);
            byte[] data = new byte[(int) file.length()];
            fin.read(data);
            fin.close();
            out = response.getOutputStream();
            out.write(data);
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

前端代碼

  • 頁面代碼
<template>
  <div>
    <el-row>
      <el-col :span="24">
        <el-card class="box-card">
          <el-row style="float: left;margin-top: 10px;margin-bottom: 10px ">
            <el-col :span="24">
              <el-button type="primary" @click="dialogVisible=true">上傳</el-button>
            </el-col>
          </el-row>
          <el-table
            stripe
            highlight-current-row
            border
            :data="fileDataList"
            style="width: 100%">
            <el-table-column
              prop="fileName"
              label="文件名"
              align="center"
              width="200">
            </el-table-column>
            <el-table-column
              prop="fileSize"
              label="文件大小"
              align="center"
              width="180">
            </el-table-column>
            <el-table-column
              prop="fileTime"
              align="center"
              label="上傳時間">
            </el-table-column>
            <el-table-column
              align="center"
              label="操作">
              <template slot-scope="scope">
                <el-button @click="downLoad(scope.row)" type="text">下載</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-col>
    </el-row>
    <el-dialog
      title="文件上傳"
      :visible.sync="dialogVisible"
      center
      width="30%">
      <div style="text-align: center">
        <el-upload
          action
          class="upload-demo"
          drag
          :on-change="fileChange"
          :auto-upload="false"
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">將文件拖到此處,或<em>點擊上傳</em></div>
          <div class="el-upload__tip" slot="tip">只能上傳jpg/png文件,且不超過500kb</div>
        </el-upload>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="httpRequest">確 定</el-button>
      </span>
    </el-dialog>
  </div>

</template>

<script>
    export default {
        name: 'file',
        data() {
            return {
                form: {
                    fileName: '',
                    current: 1,
                    size: 10
                },
                fileDataList: [],
                dialogVisible: false,
                file: ''
            }
        },
        methods: {
            // 下載文件
            downLoad(row) {
                this.$http.get(
                    '/sysFile/downLoadFile',
                    {params: {fileId: row.fileId}},
                    {responseType: "blob"}
                ).then((res) => {
                    let url = window.URL.createObjectURL(new Blob([res.data]));
                    let link = document.createElement("a");
                    link.style.display = "none";
                    link.href = url;
                    link.setAttribute("download", row.fileName); //指定下載後的文件名,防跳轉
                    document.body.appendChild(link);
                    link.click();
                }).catch(function (error) {
                    console.log(error);
                });
            },
            // 加載文件
            async getFileList() {
                this.$http.get('/sysFile/selectAll', {params: this.query}).then((res) => {
                    if (res.data.code == 0) {
                        this.fileDataList = res.data.data.records;
                        // this.total = res.data.data.total;
                    }
                }).catch(function (error) {
                    console.log(error);
                });
            },
            // 上傳文件
            httpRequest() {
                if (this.file == null) {
                    this.$message.warning('請選擇需要上傳的文件');
                    return false;
                }
                let params = new FormData();
                params.append('file', this.file);
                let config = {
                    headers: {'Content-Type': 'multipart/form-data'}
                };
                this.$http.post('/sysFile/uploadFile', params, config).then((res) => {
                    if (res.data.code == 0 || res.data.data.result == 'success') {
                        this.$message.success('文件上傳成功');
                        this.dialogVisible = false;
                        this.file = '';
                        this.getFileList();
                    }
                }).catch(function (error) {
                    console.log(error);
                });

            },
            fileChange(file, fileList) {
                this.file = file.raw;
            },
        },
        created() {
            this.getFileList();
        }
    }
</script>
<style scoped>
</style>

注:
前端下載,不建議使用超鏈接方式
比如這種的,不信可以試試,你就知道爲什麼了!

 function downloadExcel() {
    window.location.href = "/tUserHyRights/downloadUsersUrl";
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章