前言.上传和下载是最常用的开发需求,很多文章上传功能都是直接用el-upload类型上传功能,下载都是通过文件传输的,本文章所写的上传是通过element上传的组件调用后端 接口是实现,下载是通用传输的url(即上传服务器保存后的文件去下载)去返回文件去实现功能。希望对有相同需求的从业人员有帮助
一.上传
1.前端按钮的编写
<el-upload
action="#"
:headers="upload.headers"
:action="upload.url"
ref="upload"
:file-list="fileList"
:on-success="handleFileSuccess"
:on-change="change"
:on-error="error"
:auto-upload="true"
:show-file-list="false"
>
<el-button
type="info"
size="mini"
icon="el-icon-upload el-icon--right"
:loading="loadingBtn.uploadOwner"
>上传
</el-button>
</el-upload>
2.前端上传的限制
// 是否禁用上传
isUploading: false,
// 是否更新已经存在的用户数据
updateSupport: 0,
// 设置上传的请求头部
headers: {Authorization: "Bearer " + getToken()},
// 上传的地址
url: process.env.VUE_APP_BASE_API + "/ycc/store/inventoryheader/uploadFileAvator"
3.前端方法调用
// 覆盖默认的上传行为
requestUpload() {
},
error(err, file, fileList) {
console.log("err", file)
},
change(file, fileList) {
},
// 文件上传成功处理
handleFileSuccess(response, file, fileList) {
console.log("response", response);
if (response.code == 200) {
console.log("response", response);
this.resultData.detail.push(response.data);
console.log(" this.resultData.header.detail", this.resultData.detail);
}
},
handlePictureCardPreview(file) {
console.log("file", file)
},
4.上传后端的实现
@Log(title = "pc端盘点上传文件", businessType = BusinessType.INSERT)
@PostMapping("/uploadFileAvator")
public AjaxResult uploadFileAvator(HttpServletRequest request) {
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile file = multipartRequest.getFile("file");
if (file == null) {
throw new CustomException("pc端盘点上传文件失败");
}
String name = file.getOriginalFilename();
logger.debug("文件名称,{}", name);
logger.debug("文件大小,{}", file.getSize());
R<SysFile> upload = remoteFileService.upload(file);
if (upload.getCode() != 200) {
throw new CustomException("pc端盘点上传文件失败");
}
String url = upload.getData().getUrl();
FileRecord fileRecord = new FileRecord();
fileRecord.setFileUrl(url);
fileRecord.setFileName(name);
return AjaxResult.success("上传成功", fileRecord);
}
5.效果
二.下载
1.前端按钮
<el-button
type="info"
size="mini"
icon="el-icon-download el-icon--right"
@click="downloadOwner"
:loading="loadingBtn.downloadOwner"
>下载
</el-button>
2.前端请求后端
3.请求的url示例:https://ycc-cloud-test.oss-cn-shenzhen.aliyuncs.com/2023/03/29/dcf1af33-2f4d-4f6d-825e-2e3d5c51a7f4.jpeg4.后端接口返回流
//根据盘点单号查询下载的文件
@GetMapping(value = "/downloadMany")
@ApiOperation(value = "下载的文件", notes = "下载的文件")
public void downloadMany(@RequestParam("fileUrl") String fileUrl, @RequestParam("fileName") String fileName, HttpServletResponse response) {
if (!Strings.isNullOrEmpty(fileUrl)) {
InputStream inputStream = null;
ServletOutputStream outputStream = null;
try {
URL url = new URL(fileUrl);
inputStream = url.openConnection().getInputStream();
response.setCharacterEncoding("utf-8");
response.setHeader(
"Content-disposition",
"attachment; filename=" + fileName);
outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int i = inputStream.read(buffer);
while (i != -1) {
outputStream.write(buffer, 0, i);
i = inputStream.read(buffer);
}
} catch (MalformedURLException e) {
e.printStackTrace();
throw new RuntimeException("文件URL错误!");
} catch (IOException e) {
e.printStackTrace();
throw new RuntimeException("获取文件输出流失败!");
} finally {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
@GetMapping("/getAdderss")
public AjaxResult getAdderss(@RequestParam("longitude") BigDecimal longitude, @RequestParam("latitude") BigDecimal latitude) {
String address = GetDistance.getProvinceCityDistrict(longitude, latitude);
LoginUser loginUser = tokenService.getLoginUser();
Map<String, String> map = new HashMap<String, String>();
map.put("address", address);
map.put("userid", loginUser.getUserid().toString());
map.put("username", loginUser.getUsername());
map.put("nickname", loginUser.getNickname());
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = new Date();
String currentTime = simpleDateFormat.format(date);
map.put("currentTime", currentTime);
return AjaxResult.success(map);
}
@GetMapping(value = "/deleteFileByAid")
@Log(title = "文件管理删除", businessType = BusinessType.DELETE)
public AjaxResult deleteFileByAid(@RequestParam("aid") String aid) {
int j = 0;
if (!StringUtils.isEmpty(aid)) {
String[] split = aid.split(",");
Long[] temp = new Long[split.length];
for (int i = 0; i < split.length; i++) {
String s = split[i];
temp[i] = Long.parseLong(s);
}
j = fileRecordService.deleteFileRecordByIds(temp);
return toAjax(j);
}
return toAjax(j);
}
5.前端方法都是加载a标签然后触发点击下载(图片也直接下载,用windows.open(url)是直接预览)
downloadOwner() {
console.log("this.resultData.detail", this.resultData.detail);
console.log("this.selectColumn", this.selectColumn);
var checkLength = this.selectColumn.length;
console.log("checkLength", checkLength);
if (checkLength != 0) {
this.selectColumn.forEach((item, index) => {
console.log("this.detail[item]", item);
console.log("url", item.fileUrl);
console.log("url", item.fileName);
// window.open(item.fileUrl);
downloadMany(item.fileUrl,item.fileName).then(res => {
console.log(res); //
var debug = res;
if (debug) {
var elink = document.createElement('a');
elink.download = item.fileName;
elink.style.display = 'none';
var blob = new Blob([debug], { type: 'application/x-msdownload' });
elink.href = URL.createObjectURL(blob);
document.body.appendChild(elink);
elink.click();
document.body.removeChild(elink);
} else {
this.$message.error('下载异常请联系管理员');
}
}).catch(err => {
console.log(err);
});
});
} else {
this.$alert('没有勾选数据!', '提示', {
confirmButtonText: '确定'
});
}
},