瑞吉外卖(五)-文件的上传与下载

瑞吉外卖(五)

文件的上传下载

需求分析

  1. 当点击上传图片时,调用本地文件夹,可以上传jpg、jpeg、bmp等格式的图片;
    在这里插入图片描述

  2. 上传完成后,前端页面要得到上传的图片并展示出来。

在这里插入图片描述
后端需要做的任务:
3. 读取文件内容,将文件转存到本地
4. 读取刚刚存储的文件,并返回给前端展示。

前端页面设计

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>文件上传</title>
  <!-- 引入样式 -->
  <link rel="stylesheet" href="../../plugins/element-ui/index.css" />
  <link rel="stylesheet" href="../../styles/common.css" />
  <link rel="stylesheet" href="../../styles/page.css" />
</head>
<body>
   <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>
    <!-- 开发环境版本,包含了有帮助的命令行警告 -->
    <script src="../../plugins/vue/vue.js"></script>
    <!-- 引入组件库 -->
    <script src="../../plugins/element-ui/index.js"></script>
    <!-- 引入axios -->
    <script src="../../plugins/axios/axios.min.js"></script>
    <script src="../../js/index.js"></script>
    <script>
      new Vue({
        el: '#food-add-app',
        data() {
          return {
            imageUrl: ''
          }
        },
        methods: {
          handleAvatarSuccess (response, file, fileList) {
              this.imageUrl = `/common/download?name=${response.data}`
          },
          beforeUpload (file) {
            if(file){
              const suffix = file.name.split('.')[1]
              const size = file.size / 1024 / 1024 < 2
              if(['png','jpeg','jpg'].indexOf(suffix) < 0){
                this.$message.error('上传图片只支持 png、jpeg、jpg 格式!')
                this.$refs.upload.clearFiles()
                return false
              }
              if(!size){
                this.$message.error('上传文件大小不能超过 2MB!')
                return false
              }
              return file
            }
          }
        }
      })
    </script>
</body>
</html>
文件上传

结合标头中的信息
前端图片
我们可以看到,采用的是post传输,页面是/common/upload。所以在写的时候,要选择postmapping(“/upload”)注解和requestmapping(“/common”)注解. 从前端获取到的文件要以MultipartFile file参数格式发送过来,形参的命名不能随意命名,要与前端的参数一致,如下图 前端图片 所示,从前端穿的参数命名为file,因此在controller写形参的时候也要用file命名(若在参数前加入@RequestParam(“file”)注解,则可随意命名)。
然后,后端controller获取到文件后,首先读取文件名,为防止重复,为文件生成新的文件名,同时由于从前端传入的文件是临时存放的,因此需要转存到后端的服务器中。
upload代码俠
前端图片

	@Value("${reggie.path}")
    private String basePath;
	@PostMapping("/upload")
    public R<String> upload(@RequestParam("file") MultipartFile file){

        // 获取原始文件名
        String originalFilename = file.getOriginalFilename();
        // 动态获取文件后缀
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        // 使用UUID重新生成文件名,防止文件名重复造成文件覆盖
        String filename = UUID.randomUUID().toString() + suffix;


        //创建一个目录对象
        File dir = new File(basePath);
        // 判断当前目录是否存在
        if (!dir.exists()){
            //目录不存在,需要创建
            dir.mkdirs();
        }

        // file 是一个临时文件,需要把它转存在指定位置,否则本次请求完成过后临时文件会被删除
        log.info(file.toString());
        try {
            // 将临时文件转存到指定位置
            file.transferTo(new File(basePath+filename));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return R.success(filename);
    }

注意,为了方便修改,我们可以将文件存储的路径写在application.ymal中。

reggie:
  path: D:\img\
文件下载

当文件上传成功后,需求中需要将上传的图片返回到前端页面展示,因此,后端要将图片返回给前端页面展示。
结合前端页面的代码,请求的页面是download,请求方式是Get.
在这里插入图片描述
在这里插入图片描述
参数,第一个参数就是文件名称,第二个参数就是response用于返回给前端。
方法,读取,然后输出到前端。
代码如下:

/**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse response){
        // 输入流,通过输入流,读取文件内容
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(basePath + name));

            // 输出流,通过输出流将文件写会浏览器,在浏览器展示了。
            ServletOutputStream outputStream = response.getOutputStream();

            response.setContentType("image/jpeg");
            int len=0;
            byte[] bytes = new byte[1024];
            while ((len=fileInputStream.read(bytes))!=-1){
                //fileInputStream.read(bytes) ,其中bytes用于临时存放读入的字节,当读完之后,返回-1;
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }

            // 关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }


    }
文件上传需要对页面的form表单有如下要求
method = “post”采用post方式提交数据
enctype =“multipart/form-data”采用multipart格式上传文件
type=“file”使用input的file控件上传

例如:

<form method="post" action="/common/upload" enctype="multipart/form-data">
	<input name = "myFile" type = "file" />
	<input type = "submit" value="提交">
</form>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值