vue第三方地址圖片上傳+后端圖片上傳接口開發(fā)+postman測試圖片上傳
- Vue + element (el-upload)中的:http-request圖片上傳
- java后端上傳接口,利用OSS存儲(chǔ)圖片
- postman測試圖片上傳功能及方法
對比:服務(wù)端簽名后直傳
前言
使用element UI 的el-upload實(shí)現(xiàn)第三方地址圖片上傳,替換原來的action方法
一、Vue + el-upload
直接上傳方法如下:上傳圖片根據(jù)action地址請求后獲取到圖片url地址
具體方法官網(wǎng)有定義,action為必傳項(xiàng)
二、實(shí)現(xiàn)第三方地址圖片上傳
不使用action地址,又由于action為必傳項(xiàng),改為 action=" #",新增 :http-request
頁面:
<el-form :model="form">
<el-form-item label="圖片" v-model="form.imageUrl">
<el-upload
action="#"
list-type="picture-card"
:http-request="httpRequest"
:before-upload="beforeAvatarUpload"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt />
</el-dialog>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">立即創(chuàng)建</el-button>
<el-button>取消</el-button>
</el-form-item>
</el-form>
方法:
methods: {
httpRequest(data) {
console.log("自定義上傳", data);
// 封裝FormData對象
var formData = new FormData();
formData.append("file", data.file);
console.log("formData",formData);
// 調(diào)用后端接口
uploadByServer(formData).then(res => {
console.log(res);
}).catch(err=>{})
},
beforeAvatarUpload(file) {
// console.log("上傳前", file);
const isImg = file.size / 1024 / 1024 < 2;
if (!isImg) {
this.$message.error("上傳頭像圖片大小不能超過 2MB!");
}
const isType = file.type === "image/png";
const isType2 = file.type === "image/jpeg";
if (!isType && !isType2) {
this.$message.error("上傳頭像圖片格式為png或jpg");
}
return (isType || isType2) && isImg;
},
}
結(jié)果:
前端代碼:
<template>
<div>
<el-form :model="form">
<el-form-item label="圖片" v-model="form.imageUrl">
<el-upload
action="#"
list-type="picture-card"
:http-request="httpRequest"
:before-upload="beforeAvatarUpload"
>
<i class="el-icon-plus"></i>
</el-upload>
<el-dialog :visible.sync="dialogVisible">
<img width="100%" :src="dialogImageUrl" alt />
</el-dialog>
</el-form-item>
<el-form-item>
<el-button type="primary" @click="onSubmit">立即創(chuàng)建</el-button>
<el-button>取消</el-button>
</el-form-item>
</el-form>
</div>
</template>
<script>
import {uploadByServer} from "@/api/upload";
export default {
data() {
return {
form: {
imageUrl: ""
},
dialogImageUrl: "",
dialogVisible: false
};
},
methods: {
httpRequest(data) {
console.log("自定義上傳", data);
var formData = new FormData();
formData.append("file", data.file);
console.log("formData",formData);
uploadByServer(formData).then(res => {
console.log(res);
}).catch(err=>{})
},
beforeAvatarUpload(file) {
// console.log("上傳前", file);
const isImg = file.size / 1024 / 1024 < 2;
if (!isImg) {
this.$message.error("上傳頭像圖片大小不能超過 2MB!");
}
const isType = file.type === "image/png";
const isType2 = file.type === "image/jpeg";
if (!isType && !isType2) {
this.$message.error("上傳頭像圖片格式為png或jpg");
}
return (isType || isType2) && isImg;
},
handleChange(file, fileList) {
if (fileList.length > 1) {
fileList.shift();
}
},
handleRemove(file, fileList) {
console.log(file, fileList);
},
onSubmit() {
console.log("submit!");
}
},
created() {},
mounted() {}
};
</script>
}
二、后端接口
利用OSS實(shí)現(xiàn)簡單的圖片上傳功能:文章來源:http://www.zghlxwxcb.cn/news/detail-425607.html
引入oss依賴
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alicloud-oss</artifactId>
<version>2.2.0.RELEASE</version>
</dependency>
Controller層((@RequestParam MultipartFile file))
@PostMapping("/uploadByServer")
public R uploadByServer(@RequestParam MultipartFile file) {
String s = bannerServiece.uploadByServer(file);
return R.ok().put("data",s);
}
接口實(shí)現(xiàn)
public String uploadByServer(MultipartFile file) {
// Endpoint以華東1(杭州)為例,其它Region請按實(shí)際情況填寫。
String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
// 阿里云賬號AccessKey擁有所有API的訪問權(quán)限,風(fēng)險(xiǎn)很高。強(qiáng)烈建議您創(chuàng)建并使用RAM用戶進(jìn)行API訪問或日常運(yùn)維,請登錄RAM控制臺(tái)創(chuàng)建RAM用戶。
String accessKeyId = "yourAccessKeyId";
String accessKeySecret = "yourAccessKeySecret";
// 填寫B(tài)ucket名稱,例如examplebucket。
String bucketName = "examplebucket";
// 填寫Object完整路徑,完整路徑中不能包含Bucket名稱,例如exampledir/exampleobject.txt。
String objectName = "banner/uat/";
// 創(chuàng)建OSSClient實(shí)例。
OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
String url = "";
try {
// 獲取上傳文件的輸入流
InputStream inputStream = file.getInputStream();
// 獲取文件原始名稱
String filename = file.getOriginalFilename();
// 創(chuàng)建PutObjectRequest對象。
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, objectName + filename, inputStream);
// 設(shè)置該屬性可以返回response。如果不設(shè)置,則返回的response為空。
putObjectRequest.setProcess("true");
// 調(diào)用oss方法實(shí)現(xiàn)上傳
// 1、bucketName 2、上傳到oss文件路徑和文件名稱 3、文件的輸入流
// PutObjectResult putObjectResult = ossClient.putObject(bucketName, objectName + filename, inputStream);
PutObjectResult putObjectResult = ossClient.putObject(putObjectRequest);
// 獲取url地址(根據(jù)阿里云oss中的圖片實(shí)例拼接字符串) 拼接url字符串
// https://edu-leader.oss-cn-beijing.aliyuncs.com/%E4%BB%96.jpg
String uri = putObjectResult.getResponse().getUri();
// url = "https://" + bucketName + "." + "oss-cn-hangzhou.aliyuncs.com" + "/" + objectName + filename;
url = uri;
// 關(guān)閉oss
ossClient.shutdown();
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
return url;
}
三、postman測試圖片上傳
文章來源地址http://www.zghlxwxcb.cn/news/detail-425607.html
總結(jié)
到了這里,關(guān)于Vue+element Upload利用http-request實(shí)現(xiàn)第三方地址圖片上傳的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!