若依框架文件上传
前端:
采用el-upload上傳,通過回調on-change方法中上傳:
<el-upload
? ? ? ? ? ? ? ? ref="uploadRef"
? ? ? ? ? ? ? ? action="" ?
? ? ? ? ? ? ? ? accept=".xlsx, .xls"
? ? ? ? ? ? ? ? :auto-upload="false"
? ? ? ? ? ? ? ? :on-change="handleChange"
? ? ? ? ? ? ? ? :show-file-list="false"
? ? ? ? ? ? ? >
? ? ? ? ? ? ? <el-button?
? ? ? ? ? ? ? type="primary"
? ? ? ? ? ? ? size="mini"
? ? ? ? ? ? ? >上傳</el-button>
? ? ? ? ? ? ? </el-upload>
上傳方法:
? ?handleChange(file) {
? ? console.log(file)
? ? ?if(file!=null){
? ? ? ? let formData = new FormData();
? ? ? ? formData.append('file', file.raw)
? ? ? ? uploadFile(formData).then(response => {
? ? ? ? ? ? ?console.log(response)
? ? ? ? ? ? this.msgSuccess("上傳成功!");
? ? ? ? });
? ? ?}
? ? }
請求接口:
export function uploadFile(data) {
? return request({
? ? url: '/xxx/xxx',
? ? method: 'post',
? ? data: data
? })
}
后端:
? @PostMapping("/xxx")
? ? public AjaxResult uploadFile(@RequestParam("file") MultipartFile file){
String fileName = ?file.getOriginalFilename();
? ? ? ? ?? ? File file_dir= new File("d:/upload");
? ? ? ? ? ? ?if(!file_dir.exists()) {
? ? ? ? ? ? ?? ? file_dir.mkdirs();
? ? ? ? ? ? ?}
? ? ? ? ? ? ?
? ? ? ? ? ? ?int fileNamelength = file.getOriginalFilename().length();
? ? ? ? ? ? ?if (fileNamelength > FileUploadUtils.DEFAULT_FILE_NAME_LENGTH)
? ? ? ? ? ? ?{
? ? ? ? ? ? ? ? ?throw new FileNameLengthLimitExceededException(FileUploadUtils.DEFAULT_FILE_NAME_LENGTH);
? ? ? ? ? ? ?} ? ? ? ? ??
? ? ? ? ? ? ?FileUploadUtils.assertAllowed(file, MimeTypeUtils.DEFAULT_ALLOWED_EXTENSION);
? ? ? ? ? ? ?File desc = createAbsoluteFile("d:/upload", fileName);
? ? ? ? ? ? ?file.transferTo(desc);?
}
? ? private static final File createAbsoluteFile(String uploadDir, String fileName) throws IOException
? ? {
? ? ? ? File desc = new File(uploadDir + File.separator + fileName);
? ? ? ? if (!desc.getParentFile().exists())
? ? ? ? {
? ? ? ? ? ? desc.getParentFile().mkdirs();
? ? ? ? }
? ? ? ? if (!desc.exists())
? ? ? ? {
? ? ? ? ? ? desc.createNewFile();
? ? ? ? }
? ? ? ? return desc;
? ? } ? ?
總結
- 上一篇: es6 --- map的使用
- 下一篇: java 重构 if else_项目中的