瑞吉外卖项目:文件的上传与下载

2年前 (2022) 程序员胖胖胖虎阿
116 0 0

目录

一. 什么是文件上传与下载

文件上传

文件下载

二. 文件上传代码实现

API请求

三. 文件下载代码实现


一. 什么是文件上传与下载

文件上传

文件上传,是指将本地图片、视频、音频等文件上传到服务器上,可以供其他用户浏览或下载的过程。

文件上传在项目中应用非常广泛,我们经常发微博、发微信朋友圈都用到了文件上传功能。

文件上传过程中,对表单有如下规约:

  1. 采用post方式提交
  2. enctype采用multipart的格式上传文件
  3. type使用file控件上传

对于服务端接收文件主要用到Apache的两个组件:

  • commons-fileupload
  • commons-io

Spring框架中在spring-web包对文件上传进行了封装,大大简化了服务器的代码,只需在controller中声明一个MultipartFile类型的参数即可接收上传的文件。

文件下载

文件下载,就是从服务器中将图片传输至本地的过程,通过浏览器进行的文件下载,本质就是服务端将文件以流的形式写回浏览器的过程。

二. 文件上传代码实现

前端表单代码:

<div class="addBrand-container" id="food-add-app">
    <div class="container">
        <el-upload class="avatar-uploader"
                   action="/common/upload"
                   :show-file-list="false"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeUpload"
                   ref="upload">
            <img v-if="imageUrl" :src="imageUrl" class="avatar"></img>
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </div>
</div>

API请求

说明
请求URL common/download?name=

CommonController.java

package com.itheima.reggie.common;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * 文件上传与下载
 * @author jektong
 * @date 2022年05月13日 0:43
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {

    @Value("${reggie.path}")
    private String basePath;

    /**
     * 文件上传
     * @param file
     * @return
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file){
        log.info(file.toString());
        // 原始文件名
        String originalFilename = file.getOriginalFilename();
        // 截取出文件 
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 使用UUID重新生成文件名防止文件覆盖
        String fileName = UUID.randomUUID().toString() + suffix;
        // 创建一个目录对象
        File dir = new File(this.basePath);
        if(!dir.exists()){
            // 目录不存在,需要创建。
            dir.mkdir();
        }
        try {
            // 将文件输出到指定的位置
            file.transferTo(new File(this.basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }
}

需要注意的是,上传文件避免被覆盖,进行拼接一个新的文件路径,文件路径可以在配置文件中引用然后使用@Value获取配置的值即可

reggie:
  path: C:\img\

三. 文件下载代码实现

文件下载,页面端使用<img>标签展示下载的图片以及回调函数

<img v-if="imageUrl" :src="imageUrl" class="avatar"></img>

handleAvatarSuccess(response, file, fileList) {
  this.imageUrl = `/common/download?name=${response.data}`
},

文件下载代码:CommonController.java

/**
* 文件下载
*
* @param name     文件名
* @param response 文件数据
*/
@GetMapping("/download")
public void downLoad(String name, HttpServletResponse response) {
try {
    // 读取文件内容
    FileInputStream fileInputStream = new FileInputStream(new File(this.basePath + name));
    // 输出流,用于写入浏览器展示图片
    ServletOutputStream outputStream = response.getOutputStream();
    int len = 0;
    byte[] bytes = new byte[1024];
    while ((len = fileInputStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, len);
        outputStream.flush();
    }
    // 关闭资源
    outputStream.close();
    fileInputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}
}
版权声明:程序员胖胖胖虎阿 发表于 2022年9月6日 下午8:00。
转载请注明:瑞吉外卖项目:文件的上传与下载 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...