vue前端
组件部分
我这里是通过外部模拟点击触发上传的
<el-upload
class="upload-resource"
action=""
:http-request="(file)=>clickUploadFile(file,item.article_id)"
:on-success="uploadComplete"
:on-error="uploadError"
:show-file-list="false"
@click.stop.prevent
/>
<el-button style="right: 10%;position: absolute" type="primary" plain round size="mini" @click.stop.prevent="handleUpload">文件上传</el-button>
<!--下载删除文件 -->
<span v-for="(item2,index2) in tArticleFile" :key="index2">
<span style="cursor:pointer;color:#1890ff" @click="downLoadFile(item2)">{{ index2+1 }}、{{ item2.fileRealName }}</span>
<span style="cursor:pointer;float:right;color:red" @click="deleteFile(item2)">X</span>
<el-divider />
</span>
:http-request=“(file)=>clickUploadFile(file,item.article_id)” : 自己的文件上传接口函数,箭头函数可以方便传递自己的参数数据和组件原有的函数
js代码
// 上传文件
async clickUploadFile(file, article_id) {
const formData = new FormData()
formData.append('file', file.file)
formData.append('article_id', article_id)
console.log(file.file)
console.log(article_id)
//上传的后端接口
addfile(formData)
},
// 模拟点击
handleUpload() {
document.querySelector('.upload-resource .el-upload').click()
},
// 上传成功
uploadComplete() {
this.fetch(this.query)
this.$message.success('文件上传成功')
},
// 上传失败
uploadError() {
this.$message.error('上传文件失败!')
},
//下载文件
downLoadFile(item) {
downLoadFile(item.fileNewName).then(res => {
const blob = new Blob([res])
const fileName = item.fileRealName
const link = document.createElement('a')
link.download = fileName
link.style.display = 'none'
link.href = URL.createObjectURL(blob)
document.body.appendChild(link)
link.click()
URL.revokeObjectURL(link.href)
document.body.removeChild(link)
})
},
deleteFile(item) {
deleteFile(item).then(res => {
this.fetch(this.query)
this.$message.success('删除文件成功')
})
}
接口请求
export function addfile(data) {
return request({
url: 'api/ebmEventsentRel/addfile',
method: 'post',
data,
contentType: 'multipart/form-data'
})
}
export function downLoadFile(fileNewName) {
return request({
url: 'api/ebmEventsentRel/downLoadFile/' + fileNewName,
method: 'get',
responseType: 'blob'
})
}
export function deleteFile(data) {
return request({
url: 'api/ebmEventsentRel/deleteFile',
method: 'post',
data
})
}
java后台
/** 文件配置 */
private final FileProperties properties;
/**
* 文档上传
*/
@RequestMapping(value = "/addfile",method=RequestMethod.POST)
public Map<String,Object> addfile(MultipartFile file, String article_id) throws Exception {
Map<String,Object> response = new HashMap<>();
if (file.isEmpty()) throw new BadRequestException("上传的文件不能为空");
//把上传的文档放到doc文件夹下
// File directory = new File("");//设定为当前文件夹
System.out.println("properties.getPath():"+properties.getPath());
File directory_path = new File(properties.getPath().getPath());
if (!directory_path.exists()) {
directory_path.mkdirs();
throw new BadRequestException("创建文件失败");
}
//生成文件id
IdWorker idWorker=new IdWorker(0,0);
final String file_id=idWorker.nextId();
String type = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String file_path = directory_path.getPath()+File.separator+file_id+type;
File uploadfile = new File(file_path);
//写入文档
FileOutputStream os = new FileOutputStream(uploadfile);
BufferedOutputStream out = new BufferedOutputStream(os);
out.write(file.getBytes());
out.flush();
out.close();
//将文件存入数据库
tArticleFile tArticleFile=new tArticleFile();
tArticleFile.setFileId(file_id);
tArticleFile.setArticleId(article_id);
tArticleFile.setFileNewName(file_id+type);
tArticleFile.setFileRealName(file.getOriginalFilename());
tArticleFileRepository.save(tArticleFile);
response.put("code",200);
return response;
}
@ApiOperation("文档下载")
@RequestMapping(value = "/downLoadFile/{fileNewName}",method=RequestMethod.GET)
public void downLoadFile(@PathVariable("fileNewName") String fileNewName, HttpServletResponse response) throws IOException, ClassNotFoundException, IllegalAccessException, InstantiationException {
String URL = properties.getPath().getPath()+fileNewName;
System.out.println("要下载文件路径为---->" + URL);
//得到要下载的文件
File file = new File(URL);
//如果文件不存在
// if (!file.exists()) {
// //如果文件不存在,进行处理
// model.addAttribute("teacherdownloadmsg", "要下载的文件不存在,请确认");
// //这里可以自己写一个404页面
// return "errorpage/404";
// }
InputStream inputStream = null;
OutputStream outputStream = null;
//创建缓冲区
byte[] b = new byte[1024];
int len = 0;
try {
//读取要下载的文件,保存到文件输入流
inputStream = new FileInputStream(file);
outputStream = response.getOutputStream();
response.setContentType("application/force-download");
String filename = file.getName();
//设置响应头,控制浏览器下载该文件
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
response.setContentLength((int) file.length());
//循环将输入流中的内容读取到缓冲区当中
while ((len = inputStream.read(b)) != -1) {
//输出缓冲区的内容到浏览器,实现文件下载
outputStream.write(b, 0, len);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
inputStream.close();
inputStream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
outputStream = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@ApiOperation("文档删除")
@PostMapping("deleteFile")
public ResponseEntity<Object> deleteFile(@RequestBody tArticleFile tArticleFile){
//删除数据库表里得数据
tArticleFileRepository.delete(tArticleFile);
File file=new File(properties.getPath().getPath()+tArticleFile.getFileNewName());
//删除文件
file.delete();
return new ResponseEntity<>(HttpStatus.OK);
}