springboot+vue实现文件上传下载

本文实例为大家分享了springboot+vue实现文件上传下载的具体代码,供大家参考,具体内容如下

一、文件上传(基于axios的简单上传)

所使用的技术:axios、springboot、vue;
实现思路:通过h5 :input元素标签进行选择文件,获取所选选择的文件路径,new fromdata对象,设置fromdata的参数,设置axios对应的请求头,最后通过axios发送post请求后端服务。后端服务同过MultipartFile进行文件接收。具体代码如下:

前端代码:

1、创建vue对象

import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store'
import http from 'axios'
Vue.config.productionTip = false;
Vue.prototype.$http=http;
window.vm=new Vue({
 router,
 store,
 render: h => h(App)
}).$mount('#app')

2、实现上传组件

在input标签中添加改变事件监听,当发生改变时调用up方法。

<template>
 <div class="hello">
 <input
  class="file"
  name="file"
  type="file"
  accept="image/png, image/gif, image/jpeg"
  @change="up"
 />
 </div>
</template>

<script>

export default {
 name: "HelloWorld",
 props: {
 msg: String
 },
 methods: {
 up(e) {
  let file = e.target.files[0];
  alert(file.name);
  console.log(file);
  let param = new FormData(); //创建form对象
  param.append("file", file); //通过append向form对象添加数据
  console.log(param.get("file")); //FormData私有类对象,访问不到,可以通过get判断值是否传进去
  let config = {
  headers: { "Content-Type": "multipart/form-data" }
  }; //添加请求头
  this.$http
  .post("http://127.0.0.1:8081/data/up", param, config)
  .then(response => {
   console.log(response.data);
  }).catch(
   error=>{
   alert("失败");
   }
  );
 }
 }
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="less">

</style>

后端代码:

上传文件代码

 @RequestMapping(value = "/up", method = RequestMethod.POST)
 @ResponseBody
 public Result<String> uploade(@RequestParam("file") MultipartFile file) {
  try {
   log.error("开始上传!!!");
   String originalFilename = file.getOriginalFilename();
   InputStream inputStream = file.getInputStream();
   String path="d:/2020test/";
   File file1 = new File(path + originalFilename);
   if(!file1.getParentFile().exists()){
    file1.getParentFile().mkdirs();
   }
   file.transferTo(file1);
   log.info("上传成功!");
  } catch (IOException e) {
   e.printStackTrace();
  }
  Result<String> stringResult = new Result<String>();
  stringResult.setMsg("sue");
  stringResult.setData("file");
  return stringResult;
 }

二、文件下载

通过response输出流返回文件内容,核心代码设置下载文件的名字(res.setHeader(“Content-Disposition”, “attachment;filename=” + java.net.URLEncoder.encode(realFileName.trim(), “UTF-8”));)

 @RequestMapping(value = "/get", method = RequestMethod.GET)
 public void downloadFile(HttpServletResponse res) {
  String realFileName="C:/Users/xiongyi/Desktop/12.xls";
  File excelFile = new File(realFileName);
  res.setCharacterEncoding("UTF-8");
  res.setHeader("content-type", "application/octet-stream;charset=UTF-8");
  res.setContentType("application/octet-stream;charset=UTF-8");
  //加上设置大小下载下来的.xlsx文件打开时才不会报“Excel 已完成文件级验证和修复。此工作簿的某些部分可能已被修复或丢弃”
//  res.addHeader("Content-Length", String.valueOf(excelFile.length()));
  try {
   res.setHeader("Content-Disposition", "attachment;filename=" + java.net.URLEncoder.encode(realFileName.trim(), "UTF-8"));
  } catch (UnsupportedEncodingException e1) {
   e1.printStackTrace();
  }
  byte[] buff = new byte[1024];
  BufferedInputStream bis = null;
  OutputStream os = null;
  try {
   os = res.getOutputStream();
   bis = new BufferedInputStream(new FileInputStream(new File(realFileName)));
   int i = bis.read(buff);
   while (i != -1) {
    os.write(buff, 0, buff.length);
    os.flush();
    i = bis.read(buff);
   }
  } catch (IOException e) {
   e.printStackTrace();
  } finally {
   if (bis != null) {
    try {
     bis.close();
    } catch (IOException e) {
    }
   }
  }
  Result<String> stringResult = new Result<String>();
  stringResult.setMsg("sue");
  stringResult.setData("nimabi");
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • vue excel上传预览和table内容下载到excel文件中

    excel上传预览 这里会用到 npm i element-ui npm i xlsx 在vue的template中写上,排版和css看个人需求 <div> 选择文件 <input type="file" d="file_input" @change="importf(this)" accept=".csv, application/vnd.openxmlformats-officedocument.spreadshe

  • springboot整合vue实现上传下载文件

    springboot整合vue实现上传下载文件,供大家参考,具体内容如下 环境 springboot 1.5.x 完整代码下载:springboot整合vue实现上传下载 1.上传下载文件api文件 设置上传路径,如例子: private final static String rootPath = System.getProperty("user.home")+File.separator+fileDir+File.separator; api接口: 下载url示例:http://l

  • vue-cli+axios实现文件上传下载功能(下载接收后台返回文件流)

    vue-cli+axios实现附件上传下载记录: 上传: 这里用formData格式传递参数:请求成功后后台返回上传文件的对应信息. 重点是下载: ############## downloadfile(res) { var blob = new Blob([res.data], {type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document;charset=utf-8'}); //applicati

  • vue实现Excel文件的上传与下载功能的两种方式

    一.前言项目中使用到比较多的关于Excel的前端上传与下载,整理出来,以便后续使用或分析他人. 1.前端vue:模板下载与导入Excel 导入Excel封装了子组件,点击导入按钮可调用子组件,打开文件上传的对话框,上传成功后返回结果 <el-col style="padding: 10px 0 20px;"> <el-button class="pull-right" icon="el-icon-upload" type=&qu

  • SpringBoot 文件上传和下载的实现源码

    本篇文章介绍SpringBoot的上传和下载功能. 一.创建SpringBoot工程,添加依赖 compile("org.springframework.boot:spring-boot-starter-web") compile("org.springframework.boot:spring-boot-starter-thymeleaf") 工程目录为: Application.java 启动类 package hello; import org.springf

  • SpringBoot实现文件上传下载功能小结

    最近做的一个项目涉及到文件上传与下载.前端上传采用百度webUploader插件.有关该插件的使用方法还在研究中,日后整理再记录.本文主要介绍SpringBoot后台对文件上传与下载的处理. 单文件上传 // 单文件上传 @RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestParam("file") MultipartFile file) { try { if (

  • 详解SpringBoot下文件上传与下载的实现

    SpringBoot后台如何实现文件上传下载? 最近做的一个项目涉及到文件上传与下载.前端上传采用百度webUploader插件.有关该插件的使用方法还在研究中,日后整理再记录.本文主要介绍SpringBoot后台对文件上传与下载的处理. 单文件上传 / 单文件上传 @RequestMapping(value = "/upload") @ResponseBody public String upload(@RequestParam("file") Multipart

  • vue实现文件上传读取及下载功能

    本文实例为大家分享了vue实现文件上传读取及下载的具体代码,供大家参考,具体内容如下 文件的上传利用input标签的type="file"属性,读取用FileReader对象,下载通过创建a标签实现 <template> <div class="filediv"> <el-button @click="downloadFile">下载</el-button> <div id="fil

  • springboot实现文件上传和下载功能

    spring boot 引入"约定大于配置"的概念,实现自动配置,节约了开发人员的开发成本,并且凭借其微服务架构的方式和较少的配置,一出来就占据大片开发人员的芳心.大部分的配置从开发人员可见变成了相对透明了,要想进一步熟悉还需要关注源码. 1.文件上传(前端页面): <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/lo

  • 详解SpringBoot文件上传下载和多文件上传(图文)

    最近在学习SpringBoot,以下是最近学习整理的实现文件上传下载的Java代码: 1.开发环境: IDEA15+ Maven+JDK1.8 2.新建一个maven工程: 3.工程框架 4.pom.xml文件依赖项 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation

随机推荐