VUE (el-upload) +SpringBoot 实现文件上传(带参数传入后台)

VUE+SpringBoot实现文件上传(带参数传入后台)

前台:使用element-UI里面的

步骤一
先写一个文件上传的按钮(我这边是通过弹窗,将上传的文件先加入弹窗点击确定在进行上传)

<el-button
       size="mini"
       icon="el-icon-edit-outline"
       type="primary"
       @click="fileUpload(scope.row)">附件上传</el-button>

步骤二:
文件上传弹窗(这里用的是 el-upload 这个组件)

 <el-dialog
			title="提示"
			:visible.sync="dialogVisible"
			width="40%"
			>
			<span>
				<el-upload class="upload-demo"
					ref="upload"
					drag 
					action="http://localhost:8872/fileUpload" 
					multiple
					:auto-upload="false"
          with-credentials="true"
					:limit="1"
          :before-upload="handleBefore"
					:on-success="handleFilUploadSuccess"
					:on-remove="handleRemove"
          :data="uploadData"
					>
					<i class="el-icon-upload"></i>
					<div class="el-upload__text">将文件拖到此处,或<em>点击上传</em></div>
<!-- <div class="el-upload__tip" slot="tip">只能上传 Excel 文件,且不超过500kb</div> -->
	</el-upload>
			</span>
			<span slot="footer" class="dialog-footer">
				<el-button @click="dialogVisible = false">取 消</el-button>
				<el-button type="primary" @click="handleUpload">确 定</el-button>
			</span>
		</el-dialog>

在这里插入图片描述
**步骤三:**关于el-upload组件里面要用的一些方法

// el-upload相关方法
 handleRemove(file,fileList) {
      console.log("handleRemove方法清理文件")
      console.log(file,fileList);
    },
    //文件弹窗里面确定按钮
 submitUpload() {
      this.$refs.upload.submit();
    },
    // 文件上传成功时的函数
 handleFilUploadSuccess (res,file,fileList) {
      console.log(res,file,fileList)
      this.$message.success("上传成功")
      this.$refs.upload.clearFiles()
      _self.api_findAll();
    },
    handleUpdate () {
      console.log("handleUpdate方法")
      this.dialogVisible = true;
    },
    // 弹窗里面确定按钮处理文件上传的函数
    handleUpload () {
      console.log("handleUpload方法")
     // console.log(res,file)
      this.submitUpload()
      this.dialogVisible = false
    },
    // 上传前的回调函数
   handleBefore(file) {
        _self.uploadData.fileid = _self.fileUploadData;  
   },
      // 文件上传按钮
    fileUpload(row){
      _self.fileUploadData=row.id; 
      //console.log(document.cookie)
      _self.dialogVisible = true;
    },
    

步骤四
在data方法里面定义要传入后台的参数
在这里插入图片描述

后台

/**
	 * 文件上传
	 * @param multipartFile
	 * @param id 前台传过来的id
	 * @param response
	 * @param model
	 * @return
	 * @throws MyException
	 */
@PostMapping(value = "fileUpload")
public JsonResult<Object> fileUpload(HttpServletRequest request,@RequestParam(value="fileid")  String id,@RequestParam("file") MultipartFile multipartFile){
	
	if(multipartFile != null){
			//文件上传的保存路径
			String path=configBeanProp.getSoftwarePath();
			//上传的文件的保存的新名称(不含路径)
			String newFileName = multipartFile.getOriginalFilename();
			File file = new File(path+newFileName);
			 /*如果父文件夹不存在,则创建*/
	         File fileParent = file.getParentFile();
	         if (!fileParent.exists()) {
	            fileParent.mkdirs();
	         }
			try {
				//将原来的路径替换成最新的路径
				if(deviceSoftware.getSwpath()!=null && !"".equals(deviceSoftware.getSwpath())) {
					File oldFile = new File(deviceSoftware.getSwpath());
					if (oldFile.exists()) {
						oldFile.delete();
					}
				}
				//将内存的数据写到磁盘上,文件存储
				multipartFile.transferTo(file);
				FileInputStream md5testString =new FileInputStream(path+newFileName);
				//获取文件的md5值
				String md5 = DigestUtils.md5Hex(new FileInputStream(path+newFileName));
				//获取当前系统时间时分秒
				Date date=new Date();
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				String updatetimeString= sdf.format(date);
			} catch (IOException e) {
				e.printStackTrace();				
			}			
		}
		if (res) {
			jsonResult.setSuccess("文件上传成功");
		} else {
			jsonResult.setSuccess("文件上传失败");
		}
		return jsonResult;
	}
	
  • 3
    点赞
  • 30
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
你可以使用Vue.jsElement UI来实现前端界面,使用Spring Boot来处理后端逻辑来实现文件模板的上传和下载功能。 首先,你可以创建一个Vue组件来处理文件上传和下载的界面。可以使用Element UI中的Upload组件来实现文件上传功能,使用Button组件来实现文件下载功能。在上传组件中,你可以设置上传的文件类型和大小限制,并在上传成功后获取到文件的URL或者其他信息。 接下来,在后端使用Spring Boot来处理上传和下载的逻辑。你可以创建一个Controller来处理文件上传和下载的请求。在文件上传的方法中,你可以使用MultipartFile来接收上传的文件,并将其保存到服务器上的某个目录中。在文件下载的方法中,你可以根据传入的文件名或者其他标识,从服务器上读取相应的文件,并将其以流的形式返回给前端。 以下是一个简单的示例代码: 前端(Vue.js + Element UI): ```vue <template> <div> <el-upload class="upload-demo" action="/api/upload" :on-success="handleSuccess" :before-upload="beforeUpload" > <el-button type="primary">点击上传</el-button> </el-upload> <el-button type="primary" @click="downloadTemplate">下载模板</el-button> </div> </template> <script> export default { methods: { handleSuccess(response) { // 处理上传成功后的逻辑 console.log(response); }, beforeUpload(file) { // 设置上传文件的类型和大小限制 const fileType = file.type; const fileSize = file.size / 1024 / 1024; // MB const allowedTypes = ['application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document']; // 允许的文件类型 const maxFileSize = 10; // 允许的最大文件大小,单位:MB if (!allowedTypes.includes(fileType)) { this.$message.error('只能上传pdf、doc或docx格式的文件'); return false; } if (fileSize > maxFileSize) { this.$message.error(`文件大小超过了${maxFileSize}MB`); return false; } return true; }, downloadTemplate() { // 处理下载模板的逻辑 window.location.href = '/api/download'; }, }, }; </script> ``` 后端(Spring Boot): ```java @RestController @RequestMapping("/api") public class FileController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { // 处理文件上传逻辑 // 可以将上传的文件保存到服务器上的某个目录中 return "上传成功"; } @GetMapping("/download") public void downloadTemplate(HttpServletResponse response) { // 处理文件下载逻辑 // 根据文件名或者其他标识,从服务器上读取相应的文件,并将其以流的形式返回给前端 String fileName = "template.docx"; // 下载的文件名 String filePath = "/path/to/template.docx"; // 文件在服务器上的路径 try { File file = new File(filePath); InputStream inputStream = new FileInputStream(file); response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8")); IOUtils.copy(inputStream, response.getOutputStream()); response.flushBuffer(); } catch (Exception e) { e.printStackTrace(); } } } ``` 这是一个简单的示例,你可以根据自己的需求进行进一步的调整和优化。希望对你有帮助!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值