element上传图片到服务器_vue+elementui+springmvc实现图片上传功能

本文介绍了如何使用Vue.js、ElementUI组件库和SpringMVC后端框架实现图片上传功能。通过设置上传接口、限制文件类型和大小,并在成功上传后返回图片URL。
摘要由CSDN通过智能技术生成

action="http://localhost:8080/linkjb/upload/imageupload"//后台接口名

:show-file-list="false"

:on-success="handleAvatarSuccess"

:before-upload="beforeAvatarUpload">

export default {

data(){

return{

url:''

}

},

methods: {

handleAvatarSuccess(res, file) {

debugger

if(res.entity){

// let url=res.entity.replace(/\\/g,"/");

//console.log(url);

this.url = "http://localhost:8080/linkjb/images/"+res.entity;

console.log(this.url);

}else{

this.$message.error('上传错误,请联系管理员');

}

},

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;

}

},

}

}

@RequestMapping(value = "/imageupload")

public BaseResult UploadImage (HttpServletRequest request, @RequestParam(value = "file", required = false) MultipartFile file) throws IOException {

System.out.println(file);

BaseResult re =new BaseResult<>();

//获取项目根路径

String relativelyPath=System.getProperty("user.dir")+File.separator+"src"+File.separator+"main"+File.separator+"webapp";

//获取项目存放路径

String staticPath = File.separator+"static"+File.separator+"images"+File.separator+"user"+File.separator;

String path = relativelyPath + staticPath;

if(!file.isEmpty()){

String fileRealName = file.getOriginalFilename(); //获得原始文件名;

int pointIndex = fileRealName.indexOf("."); //点号的位置

String fileSuffix = fileRealName.substring(pointIndex); //截取文件后缀

String pic_time = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

Random random = new Random();

String savedFileName = pic_time.concat(fileSuffix)+random.nextInt(10000);

String savedDir = request.getSession().getServletContext().getRealPath("images"); //获取服务器指定文件存取路径

File savedFile = new File(savedDir,savedFileName );

boolean isCreateSuccess = savedFile.createNewFile();

if(isCreateSuccess){

file.transferTo(savedFile); //转存文件

re.setMessage("文件存储成功");

re.setStatus(ConstantSrting.STATUS_SUCCESS);

re.setEntity(savedFileName);

return re;

}else{

re.setStatus(ConstantSrting.STATUS_FAIL);

re.setMessage("图片存储失败");

return re;

}

}else{

re.setStatus(ConstantSrting.STATUS_FAIL);

re.setMessage("文件不能为空");

return re;

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值