Vue——文件的上传与下载

本文介绍了一个基于Vue.js前端框架和Java后端实现的文件上传与下载功能的具体实现过程。前端使用Element UI组件进行文件选择与上传,后端通过自定义控制器处理文件的上传与下载请求,并利用AjaxResult返回响应结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


文件上传

后端

Controller

package com.ruoyi.system.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.xml.ws.soap.Addressing;

@RestController
@RequestMapping("/system/upload")
public class UploadController extends BaseController {

    @Autowired
    private UploadUtil uploadUtil;

    @PostMapping(value = "/file")
    public AjaxResult uploadImage(@RequestParam("file") MultipartFile files[]) throws Exception {
        return uploadUtil.uploadImages(files);
    }
}

Util

package com.ruoyi.common.utils;

import com.ruoyi.common.core.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.ArrayList;

@Component
public class UploadUtil {

    @Value("${file.location}")
    private String baseUrl;

    /**
     * 文件上传
     * 获取文件名称,把文件存储到D:\picturePath路径下
     * @param files
     * @return
     * @throws Exception
     */
    public AjaxResult uploadImages(MultipartFile files[]) throws Exception {
        String url;
        try {
            ArrayList<String> urlList = new ArrayList<>();;
            for (int i = 0; i < files.length; i++) {
                MultipartFile multipartFile = files[i];
                String fileName = multipartFile.getOriginalFilename();
                String realPath = baseUrl;
                System.out.println("realPath==>" + realPath);

                //创建存放的目录
                File dir = new File(realPath);
                if (!dir.exists()) {
                    dir.mkdir();
                }
                File file = new File(realPath, fileName);
                multipartFile.transferTo(file);
                url = "http://localhost:8080/dev-api/file/" + fileName;
                System.out.println("url==>" + url);
               urlList.add(url);
            }
            return new AjaxResult(200, "文件传送成功", urlList);
        } catch (Exception e) {
            return new AjaxResult(500, "文件传送失败", null);
            //return new CommonResult(2001, "数据库执行有异常", null);
        }
        // return new CommonResult(200, "添加成功", url);
    }
}

AjaxResult

package com.ruoyi.common.core.domain;

import java.util.HashMap;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.StringUtils;

/**
 * 操作消息提醒
 * 
 * @author ruoyi
 */
public class AjaxResult extends HashMap<String, Object>
{
    private static final long serialVersionUID = 1L;

    /** 状态码 */
    public static final String CODE_TAG = "code";

    /** 返回内容 */
    public static final String MSG_TAG = "msg";

    /** 数据对象 */
    public static final String DATA_TAG = "data";

    /**
     * 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
     */
    public AjaxResult()
    {
    }

    /**
     * 初始化一个新创建的 AjaxResult 对象
     * 
     * @param code 状态码
     * @param msg 返回内容
     */
    public AjaxResult(int code, String msg)
    {
        super.put(CODE_TAG, code);
        super.put(MSG_TAG, msg);
    }

    /**
     * 初始化一个新创建的 AjaxResult 对象
     * 
     * @param code 状态码
     * @param msg 返回内容
     * @param data 数据对象
     */
    public AjaxResult(int code, String msg, Object data)
    {
        super.put(CODE_TAG, code);
        super.put(MSG_TAG, msg);
        if (StringUtils.isNotNull(data))
        {
            super.put(DATA_TAG, data);
        }
    }

    /**
     * 返回成功消息
     * 
     * @return 成功消息
     */
    public static AjaxResult success()
    {
        return AjaxResult.success("操作成功");
    }

    /**
     * 返回成功数据
     * 
     * @return 成功消息
     */
    public static AjaxResult success(Object data)
    {
        return AjaxResult.success("操作成功", data);
    }

    /**
     * 返回成功消息
     * 
     * @param msg 返回内容
     * @return 成功消息
     */
    public static AjaxResult success(String msg)
    {
        return AjaxResult.success(msg, null);
    }

    /**
     * 返回成功消息
     * 
     * @param msg 返回内容
     * @param data 数据对象
     * @return 成功消息
     */
    public static AjaxResult success(String msg, Object data)
    {
        return new AjaxResult(HttpStatus.SUCCESS, msg, data);
    }

    /**
     * 返回错误消息
     * 
     * @return
     */
    public static AjaxResult error()
    {
        return AjaxResult.error("操作失败");
    }

    /**
     * 返回错误消息
     * 
     * @param msg 返回内容
     * @return 警告消息
     */
    public static AjaxResult error(String msg)
    {
        return AjaxResult.error(msg, null);
    }

    /**
     * 返回错误消息
     * 
     * @param msg 返回内容
     * @param data 数据对象
     * @return 警告消息
     */
    public static AjaxResult error(String msg, Object data)
    {
        return new AjaxResult(HttpStatus.ERROR, msg, data);
    }

    /**
     * 返回错误消息
     * 
     * @param code 状态码
     * @param msg 返回内容
     * @return 警告消息
     */
    public static AjaxResult error(int code, String msg)
    {
        return new AjaxResult(code, msg, null);
    }

    /**
     * 方便链式调用
     *
     * @param key 键
     * @param value 值
     * @return 数据对象
     */
    @Override
    public AjaxResult put(String key, Object value)
    {
        super.put(key, value);
        return this;
    }
}

前端

Vue

<el-upload
  class="upload-demo"
  drag
  action="#"
  :http-request="requestUpload"
  :on-change="uploadFiles"
  multiple>
  <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>

Js

// 覆盖默认的上传行为
requestUpload() {
},
/**
 * 上传文件成功的勾子函数,文件上传成功后会调用
 * @param res 返回结果,包含code/msg/data信息等
 * @constructor
 */
uploadFiles(file){
  let formData = new FormData();
  console.log(file)
  formData.append("file", file.raw);
  uploadFile(formData).then(res => {
    let list = res.data[0].split("/")
    this.form.fileUrl = res.data[0]
    this.form.fileName = list[list.length-1]
  });
},

// 上传文件
export function uploadFile(data) {
  return request({
    url: '/system/upload/file',
    method: 'post',
    data: data
  })
}

文件下载

后端

Controller

/**
 * 下载文件
 * @param request
 * @param response
 * @throws ServletException
 * @throws IOException
 * @throws IOException
 */
@RequestMapping("/download")
public void downloadFile(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, IOException {
    // TODO Auto-generated method stub

    //获得请求文件名
    String filename = request.getParameter("filename");
    System.out.println(filename);

    //设置文件MIME类型
    response.setContentType("application/download;utf-8");
    //设置Content-Disposition
    response.setHeader("Content-Disposition", "attachment;filename="+new String(filename.getBytes("utf-8"), "iso-8859-1"));
    //读取目标文件,通过response将目标文件写到客户端
    //获取目标文件的绝对路径
    String fullFileName = "D:\\picturePath\\"+filename;
    //System.out.println(fullFileName);
    //读取文件
    InputStream in = new FileInputStream(fullFileName);
    OutputStream out = response.getOutputStream();

    //写文件
    int b;
    while((b=in.read())!= -1)
    {
        out.write(b);
    }

    in.close();
    out.close();
}

前端

Vue

<template slot-scope="scope">
  <el-button type="primary"
             size="mini"
             @click="downLoadFile(scope.row.fileName)"
             class="table-inner-button"
  >下载</el-button>
</template>

Js

/**
 * 下载文件
 * @param fileName
 */
downLoadFile(fileName){
  downloadFile(fileName).then(res=>{
    if (!res) {
      return
    }
    let url = window.URL.createObjectURL(new Blob([res]))
    let link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', fileName)
    document.body.appendChild(link)
    link.click()
    // 释放URL对象所占资源
    window.URL.revokeObjectURL(url)
    // 用完即删
    document.body.removeChild(link)
  });
},

// 下载文件
export function downloadFile(query) {
  return request({
    responseType: 'blob',
    url: '/system/file/download?filename='+query,
    method: 'get'
  })
}

总结

上传文件:用element-ui的组件进行上传,在文件发生改变的时候调用文件上传的接口,然后将返回值进行一些特殊处理。
文件下载:根据文件名称去搜寻文件,把文件以二进制流写入response,把response作为blob资源去下载下来。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

狮子座的程序员

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值