1、文件上传
1)、html
<el-form-item
:label="form.masterId ? '新文件' : '文件'"
:required="!form.masterId"
:show-message="false"
>
<el-upload
action="#"
ref="uploadFile"
:multiple="false"
:limit="1"
:http-request="fileUpload" <!-- 自定义上传方法 -->
>
<el-button size="small" type="primary">点击上传</el-button>
</el-upload>
</el-form-item>
2)、js
/**
* el-upload组件的自定义上传拦截方法
*/
fileUpload(file) {
if (file.file.size / 1024 / 1024 > 100) { //限制文件大小
this.msgWarning("文件不能大于100M");
if (this.$refs.uploadFile) {
this.$refs.uploadFile.clearFiles(); // 清空 el-upload 内的文件
}
this.updateFile = null;
return;
}
this.updateFile = file.file; //获取到需要上传的文件
},
/*
* 提交form标点数据
*/
submitForm() {
this.$refs["form"].validate((valid) => {
if (valid) {
if (!this.updateFile) {
this.msgWarning("请上传文件");
return;
}
let formData = new FormData(); //使用FormData对象上传文件,否则文件上传不到后台
formData.append("uploadFile", this.updateFile); //上传的文件
formData.append("masterComputerFile", JSON.stringify(this.form)); //其他需要提交的内容转为json字符串
addFile(formData).then((response) => { //post方法提交
this.msgSuccess("新增成功");
this.open = false;
this.getList();
});
}
});
}
3)、java代码
public void add(MultipartFile uploadFile, String masterComputerFile) {
if (uploadFile == null || uploadFile.isEmpty()) {
return AjaxResult.error("文件不能为空");
}
//转为自己需要的Java类型
MasterComputerFile file = JSONObject.parseObject(masterComputerFile, MasterComputerFile.class);
}
2、文件下载
1)、js
window.open("后端接口地址", "_blank");//不要使用Ajax访问,直接使用浏览器进行下载
2)、java
public void download(@RequestParam("filePath") String filePath, HttpServletResponse response) {
String objectName = filePath.substring(prefix.length());
OSSObject ossObject = ossClient.getObject(bucketName, objectName);
InputStream inputStream = ossObject.getObjectContent(); //这里使用字节流可以处理音频文件 字符流会导致文件打不开
response.reset();
try {
//attachment 是通知浏览器显示下载进度
response.setHeader("Content-Disposition", "attachment;filename=文件名");
response.setHeader("Content-Length", "" + ossObject.getObjectMetadata().getContentLength()); //文件长度 b
response.setContentType(ossObject.getObjectMetadata().getContentType()); //文件类型
OutputStream outputStream = response.getOutputStream();
byte[] b = new byte[1024 * 2];
int length;
while ((length = inputStream.read(b)) != -1) {
outputStream.write(b, 0, length);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
response.getOutputStream().close();
} catch (IOException e) {
e.printStackTrace();
}
}
ossClient.shutdown();
}
3)、springboot可能出现的问题
后台接口若是出现文件超出限制的提醒,可以在配置文件内添加以下内容
spring:
servlet:
multipart:
max-file-size: 100MB
max-request-size: 100MB