前端部分
limit是设置上传数量
<el-upload class="upload-demo"
:action="uploadAction"
:on-preview="handlePreview"
:on-remove="handleRemove"
:before-remove="beforeRemove" multiple
:limit="1"
:on-exceed="handleExceed"
ref="upload"
:file-list="editForm.fileList"
:http-request="getFile"
:before-upload="beforeUploadFile">
<el-button slot="trigger" size="small" type="primary">选取文件</el-button>
<el-button style="margin-left: 10px;" size="small" type="success" @click="uploadFile">上传到服务器</el-button>
<div slot="tip" class="el-upload__tip">只能上传后缀是txt的文件,且不超过1M</div>
</el-upload>
参数
data() {
return {
editForm: {
file: {},
fileList: []
}
}
}
方法
handleRemove(file, fileList) {
console.log(file, fileList);
this.editForm.file = {};
},
handlePreview(file) {
console.log(file);
},
handleExceed(files, fileList) {
this.$message.warning(`只能上传一个文件`);
},
beforeRemove(file, fileList) {
return this.$confirm(`确定移除 ${ file.name }?`);
},
//上传文件限制
beforeUploadFile(file) {
console.log(file)
let extension = file.name.substring(file.name.lastIndexOf('.') + 1)
let size = file.size / 1024 / 1024
if (extension !== 'txt') {
this.$refs.upload.clearFiles();
this.$message.warning('只能上传后缀是txt的文件');
}
if (size > 1) {
this.$refs.upload.clearFiles();
this.$message.warning('文件大小不得超过1M');
}
},
//文件上传
getFile(item) {
console.log(item.file)
this.editForm.file = item.file
},
uploadFile() {
if (this.editForm.file.name == undefined) {
this.$refs.upload.clearFiles();
this.$message.warning('请选择文件');
return;
}
let extension = this.editForm.file.name.substring(this.editForm.file.name.lastIndexOf('.') + 1)
let size = this.editForm.file.size / 1024 / 1024
if (extension !== 'txt') {
this.$refs.upload.clearFiles();
this.$message.warning('请选择文件');
return;
}
if (size > 1) {
this.$refs.upload.clearFiles();
this.$message.warning('请选择文件');
return;
}
let formData = new FormData()
console.log(this.editForm.file)
formData.append('fileName', this.editForm.file.name)
formData.append('file', this.editForm.file)
let config = {
headers: {
'Content-Type': 'multipart/form-data'
}
}
console.log(formData);
uploadFile(formData, config).then(response => {
this.editForm.impowerurl = response.filePath
// this.$refs.upload.clearFiles();
})
this.editForm.file = {};
this.editForm.fileList = [];
},
js
export function uploadFile(data) {
return request({
url: '**',
method: 'POST',
data
})
}
后端
1、本地上传
@PostMapping("/uploadFile")
public R uploadFile(@RequestParam("file") MultipartFile file) {
String fileName = file.getOriginalFilename();
if (StringUtils.isEmpty(fileName)) {
return R.error("上传文件为空");
}
// 文件上传路径
String templatePath = "F:/FilePackage/";
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
//获取文件名
String prefixName = fileName.substring(0, fileName.lastIndexOf("."));
// 解决中文问题,liunx 下中文路径,图片显示问题
fileName = UUID.randomUUID() + suffixName;
File dests = new File(templatePath);
File dest = new File(dests, prefixName + File.separator + fileName);
//文件上传-覆盖
try {
// 检测是否存在目录
if(!dests.exists()){
dests.mkdirs();
}
// getParentFile获取上一级
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
file.transferTo(dest);
//文件存储路径
String filePath = templatePath+prefixName+"/"+fileName;
return R.ok("上传成功!").put("filePath",filePath);
} catch (Exception e) {
return R.error("上传失败,文件内容为空");
}
}
2、七牛云上传
@ApiOperation("上传文件")
@PostMapping(value = "/uploadFile")
public R uploadFile(@RequestParam("file") MultipartFile file) {
String ak = "*****************";
String sk = "*****************";
String bucketname = "**";
String url = "http://**/";
if(file.isEmpty()) {
return R.error(400,"文件为空,上传失败!");
}
// 获取文件的后缀名
String suffixName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".")+1);
if(!suffixName.equals("jpg") && !suffixName.equals("png")){
return R.error(400,"请上传jpg,png文件");
}
//文件后缀
String fileExt = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1).toLowerCase();
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;
// 密钥配置
Auth auth = Auth.create(ak, sk);
// 构造一个带指定Zone对象的配置类,不同的七云牛存储区域调用不同的zone
Configuration cfg = new Configuration(Zone.zone2());
//...其他参数参考类注释
UploadManager uploadManager = new UploadManager(cfg);
// 调用put方法上传
Response res = null;
try {
res = uploadManager.put(file.getBytes(), fileName, auth.uploadToken(bucketname));
// 打印返回的信息
if (res.isOK() && res.isJson()) {
// 返回这张存储照片的地址
String fileUrl = url + JSONObject.parseObject(res.bodyString()).get("key");
return R.ok().put("filePath",fileUrl);
} else {
return R.error(400,"七牛云异常");
}
} catch (IOException e) {
e.printStackTrace();
}
return R.error(400,"七牛云异常");
}
依赖
<dependency>
<groupId>com.qiniu</groupId>
<artifactId>qiniu-java-sdk</artifactId>
<version>[7.2.0, 7.2.99]</version>
</dependency>