欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

# SpringBoot ElementUI 文件上传

程序员文章站 2022-07-05 18:43:51
...

SpringBoot ElementUI 文件上传


前端部分

1.ElementUI页面样式如下,主要提交的form表单,样式部分省略,看ElementUI 官网

<el-form :model="form">
    <el-form-item label="省份证" :label-width="formLabelWidth">
        <el-input v-model="form.idcard"
                  auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item label="姓名" :label-width="formLabelWidth">
        <el-input v-model="form.name" auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item label="地址" :label-width="formLabelWidth">
        <el-input v-model="form.address"
                  auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item label="原因" :label-width="formLabelWidth">
        <el-input v-model="form.reason"
                  auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item label="描述" :label-width="formLabelWidth">
        <el-input v-model="form.describe"
                  auto-complete="off"></el-input>
    </el-form-item>
    <el-form-item label="真实图片">
        <el-upload class="avatar-uploader"
                   //后端图片上传接口
                   action="http://localhost:8001/file/upload"
                   :show-file-list="true"
                   :on-success="handleAvatarSuccess"
                   :before-upload="beforeAvatarUpload"
                   >
            <img v-if="imageUrl" :src="imageUrl" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
    </el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
     <el-button @click="dialogFormVisible = false">取 消</el-button>
     <el-button type="primary" @click="addbukongpeople">确 定</el-button>
</div>

2.Script如下:

<script>
export default {
  data() {
    return {
      //form表单内容
      form: {
        idcard: "",
        name: "",
        describe: "",
        address: "",
        reason: "",
        image: ""
      },
      formLabelWidth: "80px",

      imageUrl: ""
    };
  },
  methods: {
    //头像上传
    handleAvatarSuccess(res, file) {
      this.imageUrl = URL.createObjectURL(file.raw);
    },
    beforeAvatarUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      //此处得到上传的文件的名字
      this.form.image = file.name;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isLt2M;
    },
	//表单提交方法
    addbukongpeople() {
      var params = {
        idcard: this.form.idcard,
        name: this.form.name,
        address: this.form.address,
        //上传图片的名字
        image: this.form.image,
        reason: this.form.reason,
        describe: this.form.describe,
        id: this.form.id
      };
      addBuKong("/task/operatebukong", params).then(res => {
        if (res.code === 200) {
          location.reload();
          this.$message(res.data);
        } else if (res.code === 500) {
          this.$message(res.data);
        }
      });
    },
  },
};
</script>

后端部分

1.SpringBoot接收图片接口FielController:该部分用kotlin代码完成,RetObj为对return 的封装

@RestController
@RequestMapping("/file")
class FileController {
    @Resource
    var fileService:FileService?=null
    /**
     * 上传图片
     * */
    @RequestMapping("/upload",method = [RequestMethod.POST])
    fun uploadImage(file:MultipartFile,req:HttpServletRequest):RetObj{
        return fileService!!.uploadImage(file,req)
    }
}

2.FieleService接口

interface FileService {
    fun uploadImage(file: MultipartFile,req: HttpServletRequest): RetObj
}

3.FileServiceImpl实现类

@Service
class FileServiceImpl: BaseService(),FileService {
    override fun uploadImage(file: MultipartFile,req: HttpServletRequest): RetObj {
        try{
            val originalFilename = file.originalFilename
            val realPath =System.getProperty("user.dir")+"\\"+"images\\"
            FileUtils.upload(file.bytes,realPath,originalFilename)
            return RetObj(true,"上传成功!")
        }catch (e:Exception){
            return RetObj(false,e.message)
        }
    }
}

4.FilUtils类实现文件复制

public class FileUtils {
    /**
     * 上传工具类
     * */
    public static void upload(byte[] file,String filePath,String fileName) throws IOException {
        File targetFile=new File(filePath);
        if(!targetFile.exists()){
            targetFile.mkdirs();
        }
        FileOutputStream fileOutputStream=new FileOutputStream(filePath+fileName);
        fileOutputStream.write(file);
        fileOutputStream.flush();
        fileOutputStream.close();
    }
}
SpringBoot静态资源访问配置
/**
 * 配置图片访问路径
 * */
@Configuration
public class MyFileConfiguration implements WebMvcConfigurer {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
	//上传的图片在J:/Documents/Desktop/实习/项目例 子/biyesheji/bigdatacar/images"下,访问路径如:		http://localhost:8001/images/test1.jpg
    //其中images表示访问的前缀。"J:/Documents/Desktop/实习/项目例   子/biyesheji/bigdatacar/images"是文件真实的存储路径
       registry.addResourceHandler("/images/**").addResourceLocations("file:J:/Documents/Desktop/实习/项目例子/biyesheji/bigdatacar/images/");
    }
}

访问地址得到静态资源如下:localhost:8001/images/test1.jpg
# SpringBoot ElementUI 文件上传

相关标签: 后端开发