Springboot -文件图片上传功能

Springboot -文件图片上传功能

典型案例:发微博,发微信朋友圈都用到文件上传功能

文件上传时,对页面的form表单有如下的要求

  • method =“post” 采用post方式提交数据
  • enctype = “multipart/form-data” 采用multipart格式长传文件
  • type = “file” 使用input的file控件上传

我采用的前端插件是Elment-ui+Vue

头部分-样式引入

<head>
    <meta charset="utf-8">
    <title>文件上传</title>

    <!-- 引入样式 -->
    <link rel="stylesheet" href="../plugins/elementui/index.css">
    <link rel="stylesheet" href="../plugins/font-awesome/css/font-awesome.min.css">
    <link rel="stylesheet" href="../css/style.css">

</head>

body-页面插件使用

<body>
<div id="app">
    //文件上传的一个插件
    <el-upload
        class="upload-demo"
        action="http://localhost/index/upload"
        :on-change="handleChange"
        :file-list="fileList">
    <el-button size="small" type="primary">点击上传</el-button>
    <div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div>
   </el-upload>
    //图片上传的一个插件
    <el-upload
            class="avatar-uploader"
            action="http://localhost/index/upload"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
        <img v-if="imageUrl" :src="imageUrl" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
    </el-upload>

</div>
</body>

script

<!-- 引入组件库 -->

<script src="../js/vue.js"></script>

<script src="../plugins/elementui/index.js"></script>

<script type="text/javascript" src="../js/jquery.min.js"></script>

<script src="../js/axios-0.18.0.js"></script>

<script>
    var vue = new Vue({
        el: '#app',
        data() {
            //文件的配置
                return {
                    fileList: [{
                        name: 'food.jpeg',
                        url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
                    }, {
                        name: 'food2.jpeg',
                        url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
                    }],
               //图片的配置
                    imageUrl: ''
                };
            },
            methods: {
                handleChange(file, fileList) {
                    this.fileList = fileList.slice(-3);
                },
                handleAvatarSuccess(res, file) {
                    this.imageUrl = URL.createObjectURL(file.raw);
                },
                beforeAvatarUpload(file) {
                    const isJPG = file.type === 'image/jpeg';
                    const isLt2M = file.size / 1024 / 1024 < 2;

                    if (!isJPG) {
                        this.$message.error('上传头像图片只能是 JPG 格式!');
                    }
                    if (!isLt2M) {
                        this.$message.error('上传头像图片大小不能超过 2MB!');
                    }
                    return isJPG && isLt2M;
                }
            }

    })
</script>
注意:其中Elment-ui可以帮我们自动上传并回显,需要更改action路径调用controller,将图片/文件的数据传给后台
    @PostMapping("/upload")
    public String upload(MultipartFile file){
        log.info(file.toString());
        return null;
    }

接受到文件信息

文件图片信息

强调:fileName = “file”,这里的fileName要和后面public String upload(MultipartFile xxx)中的xxx保持一致,建议都为file
  • 此时file还只是各临时文件,需要转存到指定的位置,否则本次请求后,临时文件会自动删除

解决方法就是:用file.transferTo(new File(…))方法将文件放置在指定目录下,可以通过yml文件配置路径解耦

//    获取yml中配置的指定路径
    @Value("${file.path}")
    private String basePath;

    @PostMapping("/upload")
    public String upload(MultipartFile file) throws IOException {
//        获取原始文件名
        String originalFilename = file.getOriginalFilename();

//        动态截取文件或图片的后缀:.jpg等
        String suffix =  originalFilename.substring(originalFilename.lastIndexOf("."));

//        为了防止文件名一样出现覆盖问题,可以使用UUID随机生成
        String fileName = UUID.randomUUID().toString()+suffix;//sadfafiuefbf.jpg

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

//        将文件转存到指定位置
        file.transferTo(new File(basePath+fileName));
//        返回文件名称
        return fileName;
    }

最后是要返回文件名称的,通过保存按钮提交表单,将图片名称存入数据库中


Springboot -文件图片下载功能

上传内容后,我们可以在response接受到上传的文件信息

  • 配置前端方法

  • 将上传的文件名获取,发出新的路径请求

     handleAvatarSuccess(response, file) {
                        this.imageUrl = `http://localhost/index/download?name=${response}`
                       //将图片存入数据库
                        this.cover = response.data
                    },
    
  • 后端的请求处理

    通过输入输出流来获取并回显到页面

  • //       文件下载
        @GetMapping("/download")
        public  void downLoad(String name, HttpServletResponse response) throws IOException {
    //       输入流,通过输入流读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(basePath+name));
    
    //        输出流,通过输出流将文件写回浏览器,在浏览器展示图片
            ServletOutputStream outputStream = response.getOutputStream();
    //        设置响应回去的文件类型
            response.setContentType("image/jpeg");
            int length = 0;
            byte[] bytes = new byte[1024];
    //        将文件内容读取到bytes数组里
            while((length = fileInputStream.read(bytes)) != -1){
    //            将内容输出
                outputStream.write(bytes,0,length);
    //            刷新
                outputStream.flush();
            }
    
    //        关闭资源
            outputStream.close();
            fileInputStream.close();
    
        }
    
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值