上传图片01

本文介绍了如何在Spring Boot应用中配置文件上传,包括修改`application.properties`设置上传限制和静态资源路径。同时展示了使用Element UI的图片上传组件实现文件上传功能,详细解释了`handleSuccess`方法中的参数含义。最后,展示了后端`UploadController`的`upload`方法,处理MultipartFile对象并保存文件。
摘要由CSDN通过智能技术生成

一、修改application.properties

#server.port=8081 修改端口
spring.datasource.url=jdbc:mysql://localhost:3306/empdb?characterEncoding=utf8&serverTimezone=Asia/Shanghai&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
#设置上传文件大小 默认1MB
spring.servlet.multipart.max-file-size=10MB
#设置静态资源文件夹
spring.web.resources.static-locations=file:d:/files,classpath:static

        #设置静态资源文件夹
        spring.web.resources.static-locations=file:d:/files,classpath:static .

        在浏览器的地址导航栏可以直接访问静态资源 如图:

 

二、页面引入

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <!-- import CSS -->
    <link rel="stylesheet" href="https://cdn.staticfile.org/element-ui/2.15.9/theme-chalk/index.css">
</head>
<body>
<div id="app">
    <h1>上传页面</h1>
    <h1><a href="/index.html">返回页面</a></h1>
    <!--请求路径 action="/upload"-->
    <!--name 代表发请求时参数的名称-->
    <!-- :on-success="handleSuccess" 作用是上传成功后调用方法为handleSuccess-->
    <el-upload
            name="pic"
            action="/upload"
            list-type="picture-card"
            :on-success="handleSuccess"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove">
        <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
    <hr>
    <!--http://locahost:8080/1d358f83-f473-44db-bb6a-0bcbd638746c.jpg-->
    <!--   <img :src="url" alt="">-->
    <!-- &lt;!&ndash;response =file.response 代表服务器响应的图片路径&ndash;&gt;
    <img v-for="f in arr" :src="f.response" alt="" style="height: 50px;width: 50px">-->

    <input type="text" placeholder="图片描述" v-model="intro">
    <input type="button" value="发布图片" @click="send()">
</div>
</body>
<!-- import Vue before Element -->
<script src="https://cdn.staticfile.org/vue/2.6.14/vue.min.js"></script>
<!-- import JavaScript -->
<script src="https://cdn.staticfile.org/element-ui/2.15.9/index.min.js"></script>
<!--import Axios-->
<script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
<script>
    let v = new Vue({
        el: '#app',
        data: function () {
            return {
                url: "",
                dialogImageUrl: '',
                dialogVisible: false,
                arr: [],
                intro: ""
            };
        },
        methods: {
            handleRemove(file, fileList) {
                console.log(file, fileList);
                //当页面中删除图片的时候需要向服务器发送删除请求,让服务器把files文件夹中的图片删除.
                axios.get("/remove?url=" + file.response).then(function () {
                    console.log("删除完成")
                })
            },
            handlePictureCardPreview(file) {
                this.dialogImageUrl = file.url;
                this.dialogVisible = true;
            },
            /*handleSuccess(response,file,fileList)
            1.response 返回服务器响应数据(文件路径)
            2.file 代表是当前上传成功的文件对象
            3.fileList 代表上传成功的所有文件对象(数组)*/
            handleSuccess(response, file, fileList) {
                console.log("图片路径" + response)
                /*response没有.data与axios不一样*/
                /*response ==file.response*/
                v.arr.push(file.response);
                console.log(response);
            },
            send() {
                let imge = {intro: v.intro, urls: v.arr.toString()};
                axios.post("insert", imge).then(function () {
                    alert("ok");
                })

            }
        }
    })
</script>
</html>

        使用element图片上传模板时:action="/upload"为请求路径, name 代表发请求时参数的名称.

        handleSuccess(response,file,fileList),handleSusses为组件固有方法(传输成功后会执行的方法),里面存放着对象,file,数组file,response是file的路径名.
            1.response 返回服务器响应数据(文件路径)
            2.file 代表是当前上传成功的文件对象
            3.fileList 代表上传成功的所有文件对象(数组)

三、后端获取

@RestController
public class UploadController {
    @RequestMapping("/upload")
    public String  upload(MultipartFile pic) throws IOException {
        System.out.println("pic = " + pic);
        //得到文件的原始文件名    a.jpg
        String filename = pic.getOriginalFilename();
        System.out.println(filename);

        //得到后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        System.out.println("suffix = " + suffix);

        //得到唯一的文件名
        filename = UUID.randomUUID() + suffix;
        System.out.println("filename = " + filename);

        //保存图片路径
        //创建文件夹路径
        String dirPath = "d:/files";
        File file = new File(dirPath);
        if (!file.exists()) {
            file.mkdirs();
        }
        //创建完整路径 d:/files/xxxx.jpg
        String filePath=dirPath+'/'+filename;
        //把文件保存到指定路径
        pic.transferTo(new File(filePath));

        return "/"+filename;
    }

        此时的pic就是封装好的图片对象,可以直接保存,或者对对象进行操作. 

        MultipartFie 是SpringMVC的组件,用于文件的上传操作,不使用组件就需要使用Http Servlet Request 来接受页面传输过来的数据,再转换为File类的文件.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值