vue+axios+java實現文件上傳功能
本文實例為大傢分享瞭vue+axios+java實現文件上傳的具體代碼,供大傢參考,具體內容如下
背景
vue.js + axios + element前端,Java後臺實現的文件上傳,簡單例子
前端代碼
document.vue
<template> <div> <el-row class="action-row"> <el-col :span="9"> <el-button type="primary" icon="el-icon-plus" @click="add" size="medium">新增</el-button> </el-col> </el-row> <!-- 列表 --> <el-row> <el-table :data="docs" ref="docs" style="width: 100%" stripe @sort-change="sort" v-loading="loading"> <el-table-column prop="docFileName" label="文件名稱" sortable align="center" min-width="10%"></el-table-column> <el-table-column prop="docFileType" label="文件類型" sortable align="center" min-width="10%"></el-table-column> <el-table-column prop="createTime" label="上傳時間" sortable align="center" min-width="10%"></el-table-column> </el-table> <div class="pagination"> <el-pagination @size-change="handleSizeChange" @current-change="handlePageChange" :current-page="page" :page-size="limit" :total="total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :background="true" ></el-pagination> </div> </el-row> <!-- 新建按鈕彈出框 --> <el-dialog title="上傳附件" :visible.sync="editvisible" :append-to-body="true" width="450px"> <el-form :model="gtsDocument" :rules="rules" ref="gtsDocument" label-width="120px" label-position="left" size="small" class="edit-form"> <el-form-item label="上傳附件" prop="file"> <el-upload ref="upload" action="doUpload" :limit="limitNum" :auto-upload="false" :on-change="fileChange" :on-exceed="exceedFile" :file-list="fileList"> <el-button size="small" plain>選擇文件</el-button> </el-upload> </el-form-item> </el-form> <div slot="footer" class="dialog-footer"> <el-button @click="editvisible = false">取消</el-button> <el-button type="primary" @click="save">確定</el-button> </div> </el-dialog> </div> </template> <script> import { list, del, create } from "@/api/gts/document"; export default { name: "GtsDocument", data() { return { editvisible: false, // 新增彈出框顯示標識:默認不顯示 gtsDocument: { // 隨附單據表單 docType: "", docNo: "", gtsId: "", taskId: "", file: "" }, isupdate: false, limitNum: 1, fileList: [], docs: [], loading: false, page: 1, limit: 10, total: 0, rules: {}, }; }, created: function() { this.search(); }, methods: { search() { // 初始化列表 list(this.page, this.limit, this.$route.query.gtsId).then(v => { if ("ok" == v.data.msg) { this.docs = v.data.rows; this.total = v.data.total; } }); }, // 新增按鈕點擊事件 add() { this.editvisible = true; this.$nextTick(() => { this.isupdate = false; this.$refs.gtsDocument.resetFields(); }); }, // 文件超出個數限制時的校驗 exceedFile(files, fileList) { this.$notify.warning({ title: this.$t("com.warning"), message: this.$t("com.onlySelect") + `${this.limitNum} ` + this.$t("com.someFile") }); }, // 文件狀態改變時的事件 fileChange(file, fileList) { this.gtsDocument.file = file.raw; }, // 保存 save() { this.$refs["gtsDocument"].validate(valid => { if (valid) { let formData = new FormData(); let file = this.gtsDocument.file; formData.append("file", file); if (!file) { return this.$message.warning('請選擇上傳附件'); } create(formData).then(resp => { if ("ok" == resp.data.msg) { this.editvisible = false; this.$message.success('數據保存成功'); this.search(); this.$refs.upload.clearFiles(); } else { this.$message.error('保存失敗'); } }); } }); }, handlePageChange(i) { this.page = i; this.search(); }, handleSizeChange(i) { this.limit = i; this.search(); }, } }; </script> <style rel="stylesheet/css"> .setting-form .el-form-item__label { padding-right: 30px; } </style>
document.js
import http from '@/utils/request' import axios from 'axios' export function create(formData) { return axios({ url: 'http://localhost:8080/solvay-ecustoms//gts/documents/add', method: 'post', data: formData, withCredentials: true // cros with cookie }) } export function list(page, limit, id) { return http.post('gts/documents', { page, limit, id }) }
後臺代碼
controller層
/** * <p>Description: 附件上傳</p> * @param file 上傳附件 * @return */ @ResponseBody @PostMapping("/documents/add") public String addAttach(@RequestParam("file") MultipartFile file) throws IOException { // 獲取文件名稱 String fileName = file.getOriginalFilename(); if (StringUtils.isBlank(fileName)) { return jsonfailed("文件不能為空"); } // 獲取文件的大小 long fileSize = file.getSize(); if (fileSize > 10 * 1024 * 1024) { return jsonfailed("上傳文件大小超出限定大小10M"); } // 獲取文件的擴展名 // String extension = FilenameUtils.getExtension(fileName); // 獲取配置路徑 String path = "D:/home/ecustoms/upload/"; String newPath = path + UUID.randomUUID().toString().replaceAll("-", "") + "\\"; File newDir = new File(newPath); if (!newDir.exists()) { newDir.mkdirs(); // 目錄不存在的情況下,創建目錄 } File newFile = new File(newDir, fileName); //通過CommonsMultipartFile的方法直接寫文件(註意這個時候) file.transferTo(newFile); return "ok"; }
實現截圖如下
以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。
推薦閱讀:
- elementUI自定義上傳文件功能實現(前端後端超詳細過程)
- 解析element-ui中upload組件傳遞文件及其他參數的問題
- Vue封裝通用table組件的完整步驟記錄
- 關於el-table表格組件中插槽scope.row的使用方式
- vue項目中form data形式傳參方式