目录

一、前端代码实现        

二、后端代码实现

三、调试效果实现

一、前端代码实现        

        废话不多说直接上代码

:action="'http://localhost:8080/files/upload'"

list-type="picture-card"

limit="1"

:on-exceed="limitError"

:on-success="imgSuccess"

:on-error="imgError"

>

        这里用了elementUI的一个简单的例子,自己又改了一些,简单讲解一下

        action: 头像上传向后端发送的地址,这里后端采用了本地上传

        list-type: 即文件列表的类型,就是上传后文件的样式是图片还是文字的格式

        limit: 上传数量的限制,这里仅可上传一张图片

        on-exceed: 上传超过限制触发的函数

        on-success: 上传成功触发的函数

        on-error: 上传失败触发的函数

        更多参数可以参照:组件 | Element

        相对应的函数如下:

// 上传成功

imgSuccess(res, file) {

this.imageUrl = res.data;

this.form.image = this.imageUrl;

console.log(res.data);

},

// 上传失败

imgError(res) {

this.$message({

type: "error",

message: "附件上传失败",

});

},

// 上传数量超限

limitError() {

this.$message({

type: "error",

message: "图片仅可上传一张",

});

},

        比较重要的是上传成功后的函数imgSuccess,此函数需要根据实际项目中你的form表单的值或者构建的data进行绑定操作,确保图片地址能被后端存储便于后续展示

二、后端代码实现

/**

* 文件上传

*/

@PostMapping("/upload")

public Result upload(MultipartFile file) {

if(file == null || file.isEmpty()) {

return Result.error(400,"上传文件为空");

}

String flag;

synchronized (FileController.class) {

flag = System.currentTimeMillis() + "";

ThreadUtil.sleep(1L);

}

String fileName = file.getOriginalFilename();

try {

if (!FileUtil.isDirectory(filePath)) {

FileUtil.mkdir(filePath);

}

// 文件存储形式:时间戳-文件名

FileUtil.writeBytes(file.getBytes(), filePath + flag + "-" + fileName);

System.out.println(fileName + "--上传成功");

System.out.println("文件上传地址"+filePath);

} catch (Exception e) {

System.err.println(fileName + "--文件上传失败");

return Result.error(400,"文件上传失败");

}

String http = "http://" + ip + ":" + port + "/files/";

return Result.success(http + flag + "-" + fileName);

}

        很普通的一个文件上传接口,仅接收一个文件流并进行本地存储后名称为:时间戳-文件名,

后端进行测试没有问题

三、调试效果实现

        

 

前端显示图片上传成功

精彩内容

评论可见,请评论后查看内容,谢谢!!!评论后请刷新页面。