项目中展示的效果
如下图,上传自己的附件,有要求上传类型,以及上传的大小
一、后端文件上传
@PostMapping("/upload")
public AjaxResult uploadFile(@RequestParam(name = "file",value = "file") MultipartFile file) throws Exception {
try {
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
String url = serverConfig.getUrl() + fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("url", url);
ajax.put("fileName", fileName);
ajax.put("newFileName", FileUtils.getName(fileName));
ajax.put("originalFilename", file.getOriginalFilename());
return ajax;
} catch (Exception e) {
return AjaxResult.error(e.getMessage());
}
}
二、前端代码
在写api接口的时候,需要注意文件上传的请求头(url是根据我实际中的项目路径写的)
export function uploadFile(data){
return request({
url:'/system/applications/upload',
method:'post',
headers:{
'Content-Type':'multipart/form-data;',
},
data: data
});
}
接下来就是前端页面的代码,
采用的是el-upload进行文件的上传,
http-request:是自定义文件上传(在项目中根据实际情况),
on-success:文件上传成功
on-error:文件上传失败
before-upload:在上传文件之前的判断,比如说判断上传的文件的大小是否是在规定区域,上传的文件的类型是否是规定的doc类型
multiple:limit:是限制上传文件的数量
on-exceed:代表着文件上传的限制,比如说,你已经上传了一份文件,如果再次上传就会限制,给出警告
<el-upload
class="upload-demo"
action=""
:http-request="handleFileUpload"
:on-success="handleSuccess"
:on-error="handleError"
:before-upload="beforeUpload"
multiple
:limit="1"
:on-exceed="handleExceed"
>
<el-button slot="trigger" size="small" type="primary">上传附件简历</el-button>
<div slot="tip" class="el-upload__tip">只能上传dox,doxc文件,且不超过500kb</div>
</el-upload>
具体的实现逻辑:如下代码
beforeUpload(file) {
const isDocxOrDoc = file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' || file.type === 'application/msword';
const isLt2M = file.size / 1024 / 1024 < 0.5;
if (!isDocxOrDoc) {
this.$message.error('只能上传.docx,.doc文件!');
}
if (!isLt2M) {
this.$message.error('上传文件大小不能超过 500KB!');
}
return isDocxOrDoc && isLt2M;
},
// 手动发送文件上传请求
async handleFileUpload(file) {
try {
const response = await uploadFile(file); // 调用定义的API方法,并传入文件对象
if (response.code === 200) {
this.handleSuccess(response,file);
} else {
this.handleError('文件上传失败') // 显示错误信息
}
} catch (error) {
console.error('文件上传失败:', error);
}
},
handleSuccess(response,file,fileList) {
console.log('上传成功:', response);
this.form.fileurl=response.url
},
handleError(err, file, fileList) {
console.error('上传失败:', err);
},
handleExceed(files, fileList) {
// 当选择的文件超过限制时的处理逻辑
this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
在文件上传的过程中,因为还涉及到其他的新增,所以在handleSucess中需要this.form.fileurl=response.url,这里的form是表单,将返回的url赋值给表单中的fileurl,实现在文件上传和内容的新增操作。