若依框架文件上传

1年前 (2023) 程序员胖胖胖虎阿
104 0 0

前端:

采用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;
    }    

版权声明:程序员胖胖胖虎阿 发表于 2023年3月21日 上午10:16。
转载请注明:若依框架文件上传 | 胖虎的工具箱-编程导航

相关文章

暂无评论

暂无评论...