vue elementui springboot 上传文件

11 篇文章 0 订阅
4 篇文章 0 订阅

vue部分:

 <el-form-item label="附件:" prop="file">
                <el-upload
                  action=""
                  class="upload-demo"
                  accept=".jpg,.png,.xls,.xlsx,.ppt,.pdf,.doc,.docx,.txt"
                  :before-upload="beforeUpload"
                  :before-remove="beforeRemove"
                  :file-list="fileList"
                  :on-remove="afterRemove"
                  :limit="1"
                >
                  <el-button
                    slot="trigger"
                    class="el-icon-upload"
                    size="small"
                    type="primary"
                    >选取文件</el-button
                  >
                  <div slot="tip" class="el-upload__tip">
                    只能上传小于2M的jpg/png/excel/word/txt/ppt/pdf文件
                  </div>
                </el-upload>
 </el-form-item>

相应的js:

data() {
    return {
      fileList: [], // 用来存放上传的文件
      experiment: {      
        file: '',
      },
      },
  },

methods:{
 beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}?`);
    },
    beforeUpload(file) {
      // 将要上传的值赋给experiment,当然也可以直接通过Url传递,看具体需求
      this.experiment.file = file;
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB!');
      }
      return isLt2M;
    },
    afterRemove() {
      this.fileList = [];
      this.experiment.file = '';
    },
}

 

上传触发的方法:

 const fd = new FormData();
    fd.append('reportFile', reportFile);
    fd.append('experimentReport', JSON.stringify(experimentReport));
    const config = {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    };
    return this.$axios.$put(experimentReportUri.updateUrl, fd, config);

后台controller:

  @PutMapping
    ResponseEntity updateReport(KeycloakAuthentication principal,
                                @RequestParam(value = "experimentReport") String experimentReport,
                                @RequestParam(value = "reportFile", required = false) MultipartFile reportFile) throws IOException;

 主要代码:

        String staticPath = ResourceUtils.getURL("classpath:static").getPath();
        // 获取static文件的路径 F:/workplace/ideaPlace/imbs-e/target/classes/static
        staticPath = staticPath.substring(1);
        System.out.println("获取static文件夹的路径 "+staticPath);
        String fileName = reportFile.getOriginalFilename();

        //将(年-月-日)作为文件夹
        LocalDate now = LocalDate.now();
        // now().toString()  2019-11-14
        String uploadFoldName = staticPath + File.separator + now.toString();
        //创建文件夹
        File uploadFold = new File(uploadFoldName);
        if (!uploadFold.exists() || !uploadFold.isDirectory()) {
            // 如果不存在或者不是文件夹 则创建文件夹
            uploadFold.mkdirs();
        }
        //上传文件到指定目录(因为linux和windows标识符不同\和/,所以用File.separator)
        File file = new File(uploadFold + File.separator + fileName);
        reportFile.transferTo(file);
        // 获取最后保存的路径 F:\workplace\ideaPlace\imbs-e\target\classes\static\2019-11-13\jixu.txt
        String getSavePath = file.getAbsolutePath();
        System.out.println("文件保存的本地路径为:"+getSavePath);
        // 前端访问的路径    \static\2019-11-13\jixu.txt
        String getWebPath = getSavePath.substring(getSavePath.lastIndexOf("static") - 1);
        System.out.println("前端访问的uri为:"+getWebPath);

 

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是Vue ElementUI和Spring Boot实现文件上传的前后端代码示例: 前端代码: ```vue <template> <el-upload class="upload-demo" action="/api/upload" :headers="{ Authorization: 'Bearer ' + token }" :data="{ name: 'avatar' }" :on-success="handleSuccess" :before-upload="beforeUpload"> <el-button slot="trigger" size="small" type="primary">上传文件</el-button> <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div> </el-upload> </template> <script> import axios from 'axios'; export default { data() { return { token: '', } }, mounted() { this.token = localStorage.getItem('token'); }, methods: { beforeUpload(file) { const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'; const isLt500K = file.size / 1024 < 500; if (!isJPG) { this.$message.error('上传头像图片只能是 JPG/PNG 格式!'); } if (!isLt500K) { this.$message.error('上传头像图片大小不能超过 500KB!'); } return isJPG && isLt500K; }, handleSuccess(res) { if (res.code === 0) { this.$message.success('上传成功'); } else { this.$message.error('上传失败'); } } } } </script> ``` 后端代码(Spring Boot): ```java @RestController public class FileUploadController { private static final Logger logger = LoggerFactory.getLogger(FileUploadController.class); @Value("${file.upload-dir}") private String uploadDir; @PostMapping("/api/upload") public ResponseEntity<?> uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("name") String name) { if (file.isEmpty()) { return ResponseEntity.badRequest().body("上传失败,请选择文件"); } String fileName = name + "_" + System.currentTimeMillis() + "_" + file.getOriginalFilename(); try { // 保存文件到指定目录 Path path = Paths.get(uploadDir + fileName); Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING); } catch (IOException e) { logger.error("文件保存失败", e); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件保存失败,请重试"); } logger.info("文件上传成功:{}", fileName); return ResponseEntity.ok().body("文件上传成功"); } } ``` 以上代码示例中,前端代码使用了Vue ElementUI的el-upload组件实现文件上传,设置了文件类型和大小的限制,并通过axios发送文件上传请求,同时在请求头中携带了JWT Token和其他参数。后端代码使用了Spring Boot中的MultipartFile和Files类处理文件上传请求,将上传的文件保存到指定目录中,并返回上传结果和文件信息。其中,上传目录的路径通过@Value注解从配置文件中读取。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值