springboot+vue实现图片的上传和选择

依赖导入

 <dependency>
        <groupId>cn.hutool</groupId>
        <artifactId>hutool-all</artifactId>
        <version>5.7.7</version>
    </dependency>

文件上传和下载

在springboot项目下的controller层定义一个FileController类实现文件的上传和下载功能,如下:

@RestController
@RequestMapping("/files")
public class FileController {
    @Value("${server.port}")
    private String port;
    private static final String ip = "http://localhost";

    /**
     * 上传接口
     * @param file
     * @return
     */

    @PostMapping("/upload")
    public Result<?> upload(MultipartFile file){
        String originalFilename = file.getOriginalFilename();//获取源文件的名称
	//        定义文件的唯一标识(前缀)
        String flag = IdUtil.fastSimpleUUID();

        String rootFilePath = System.getProperty("user.dir")+"/daxiongmao_backend/src/main/resources/files/"+flag+"_"+originalFilename;//获取文件上传的路径
        try {
            FileUtil.writeBytes(file.getBytes(),rootFilePath);//把文件写入该路径
        } catch (IOException e) {
            e.printStackTrace();
        }
        String url = ip+":"+port+"/files/"+flag;
        return Result.success(url);//返回结果url
    }

    /**
     * 下载接口
     * @param flag
     * @param response
     */
    @GetMapping("/{flag}")
    public void getFiles(@PathVariable String flag, HttpServletResponse response){
        OutputStream os;//新建一个输出对象
        String basePath = System.getProperty("user.dir")+"/daxiongmao_backend/src/main/resources/files/";//文件路径
        List<String> fileNames = FileUtil.listFileNames((basePath));//获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");//找到根参数一致的文件

        try {
            if (StrUtil.isNotEmpty(fileName)){
                response.addHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode(fileName,"UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);//通过文件路径读取文字节流
                os = response.getOutputStream();//通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        }catch (Exception e){
            System.out.println("文件下载失败");
        }
    }
   }

vue上传图片

在与后端的controller层的添加方法相对应,在vue中通过表单输入添加的信息,action="http://localhost:8081/files/upload"是对于FileController中文件上传的地址。

   <el-form-item label="头像">
            <el-upload ref="upload" action="http://localhost:8081/files/upload" :on-success="filesUploadSuccess">
              <el-button type="primary">点击上传</el-button>
        </el-upload>
      </el-form-item>

在script中实现方法与后端对接:

export default {
name: 'User',
 components: {

 },
  data() {
	 return {
	 form:[]
	 }
},
 methods:{
 save(){
 request.post("/api/user",this.form).then(res =>{
      console.log(res);
      if (res.code==='0'){
        this.$message({
          type: "success",
          message: "新增成功"
        })
      }else {
        this.$message({
          type: "error",
          message: res.msg
        })
      }
 },
filesUploadSuccess(res){
  console.log(res);
  this.form.picture = res.data;
  this.load();
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值