介绍:当在浏览器打开图片选择弹出框,选中图片后点击确定按钮就会立刻上传。
代码:
选取文件
(只能上传jpg/png格式图片,且图片大小不超过500KB)
imageUpload:function(param) {
let that = this;
// 先判断图片大小
const _file = param.file;
const _fileSize = _file.size < 1024 * 500;
if (!_fileSize) {
that.$message.warning("请上传500KB以下的图片文件");
return false;
}
// 参数
let params = new FormData();
params.append('questionImages', _file);
that.$axios({
url: api.uploadQusImages,//后台接口
method: "post",
data: params,
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(function(res) {
if (res.data.code == "ok") {
that.$message.success('上传成功');
}else{
that.$message.error('上传失败');
}
})
.catch(function(err) {
that.$message.error('系统内部异常');
});
},
解释:
accept:自动过滤不符合图片,
multiple 支持批量上传
action="#" 上传地址,可以不用但是一定要写
:http-request="imageUpload" 覆盖默认的上传行为,可以自定义上传的实现
2、手动上传
介绍:选择图片,展示待上传图片列表,点击上传按钮,上传至图片服务器
代码:
选取文件
上传到服务器
只能上传jpg/png格式图片,且图片大小不超过2MB
vue data 中定义fileLists[],
submitUpload() {
let that = this;
let params = new FormData();
// 注意此处对文件数组进行了参数循环添加
if(that.fileLists.length>0){
that.fileLists.forEach(function (file) {
params.append('questionImages', file.raw);
})
}else{
that.$message.warning("当前没有合适图片可以上传");
}
that.$axios({
url: api.uploadQusImages,
method: "post",
data: params,
headers: {
"Content-Type": "multipart/form-data"
}
})
.then(function(res) {
if (res.data.result == "ok") {
that.$message.success('上传成功!');
}
})
.catch(function(err) {
that.$message.error('网络请求异常!');
});
},
handleRemove(file, fileList) {
this.fileLists = fileList;
},
handlePreview(file, fileList) {
let that = this;
if (file.raw.type != 'image/jpg'&& file.raw.type != 'image/png') {
that.$message.error('图片只能是jpg/png格式!');
return;
}
if (file.raw.size > 1024 * 1024 * 2) {
that.$message.error('上传文件大小不能超过 2MB!');
return;
}
that.fileLists = fileList;
},
fileExceed:function(files, fileList){
this.$message.warning(`当前限制选择 9 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`)
},
清空上传文件:
that.fileLists = [];
this.$refs['upload'].clearFiles();
@PostMapping(value="/uploadQusImages",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public Map uploadQusImages(@RequestParam("questionImages") MultipartFile[] questionImages){
if(questionImages != null && questionImages.length > 0){
return questionManage.uploadQusImages(questionImages);
}else{
log.info("questionImages is null");
Map map = new HashMap();
map.put("code", Constants.RESULT_NULL);
return map;
}
}
注意事项:阿里云OSS上传其实不支持图片批量上传,所以将图片文件循环,转化成文件流,在循环中进行单图片上传操作。
public Map uploadQusImages(MultipartFile[] questionImages) {
Map map = new HashMap();
List listImgDetail = new ArrayList();
try {
for(MultipartFile file:questionImages){
String fileName = file.getOriginalFilename();
InputStream fileStrem = file.getInputStream();
String fileUrl = AliyunOSSUtil.uploadStemImage(fileStrem,fileName);
if(!Constants.RESULT_ERROR.equals(fileUrl)){
listImgDetail.add(imgDetail);
}
}
// 将上传成功图片全部添加到数据库中
Result result = imgGroupManage.insertImgDetail(listImgDetail);
// 图片插入结果
if((Constants.RESULT_OK).equals(result.getResult())){
map.put("code",Constants.RESULT_OK);
map.put("data",listImgDetail);
}else{
map.put("code",Constants.RESULT_ERROR);
}
} catch (IOException e) {
map.put("code", Constants.RESULT_ERROR);
log.error(e.getMessage());
}
return map;
}
public static String uploadStemImage(InputStream inputStreamFile,String fileName){
// 新建一个OSS对象
OSSClient ossClient = new OSSClient(endpoint,accessKeyId,accessKeySecret);
try {
//bucket容器不存在,就创建
if(! ossClient.doesBucketExist(bucketname)){
ossClient.createBucket(bucketname);
CreateBucketRequest createBucketRequest = new CreateBucketRequest(bucketname);
createBucketRequest.setCannedACL(CannedAccessControlList.PublicRead);
ossClient.createBucket(createBucketRequest);
}
//创建文件路径,DateTimeUtil时间工具类
String fileUrl = DateTimeUtil.getNowDateString2() + "/" + UUID.randomUUID().toString().replace("-","")+"-"+fileName;
//上传文件
PutObjectResult result = ossClient.putObject(new PutObjectRequest(bucketname, fileUrl, inputStreamFile));
log.info("========OSS上传文件结果:"+result);
//设置权限 这里是公开读
ossClient.setBucketAcl(bucketname,CannedAccessControlList.PublicRead);
if(null != result){
log.info("==========OSS文件上传成功,文件名:"+fileUrl);
// 返回文件url访问路径
return filehost+"/"+fileUrl;
}else{
log.info("==========OSS文件上传失败==========");
return Constants.RESULT_ERROR;
}
}catch (OSSException oe){
log.error(oe.getMessage());
return Constants.RESULT_ERROR;
}catch (ClientException ce){
log.error(ce.getMessage());
return Constants.RESULT_ERROR;
}finally {
//关闭 ossClient
ossClient.shutdown();
}
}
com.aliyun.oss
aliyun-sdk-oss
2.4.0
commons-fileupload
commons-fileupload
1.3.1
总结:关于阿里云上传配置信息请查看该博客:https://blog.csdn.net/CoderYin/article/details/90173118
// 文件上传大小后台限制
spring:
servlet:
multipart:
max-file-size: 500k
max-request-size : 200Mb