【每日一练】上传文件小案例

自定义文件上传按钮思路:

1.隐藏file表单 (设置display为none)

2.给自定义按钮注册点击事件,点击注册file表单默认点击事件

触发注册点击事件:dom元素.onclick()

触发默认点击事件:dom元素.click()

结构:

 <div class="thumb-box">
    <!-- 头像 -->
    <img src="./images/cover.jpg" class="img-thumbnail thumb" alt="" />
    <div class="mt-2">
      <!-- 文件选择框 -->
      <!-- accept 属性表示可选择的文件类型 -->
      <!-- image/* 表示只允许选择图片类型的文件 -->
      <input type="file" id="iptFile" accept="image/*" style="display:none" />
      <br />
      <!-- 选择头像图片的按钮 -->
      <!-- <button class="btn btn-primary" id="btnChoose">
        选择 & 上传图片
      </button> -->
      <label for="iptFile">
        <img src="./images/1.png" width="50px" height="50px" alt="">
      </label>
    </div>
  </div>

代码如下:

//1.给file表单注册onchange事件:选择文件触发
    document.querySelector('#iptFile').onchange = function () {
//2.获取用户选择的文件 this.files[0]
//3.创建FormData对象,把文件添加到fd对象
      let fd = new FormData()
//4.调用append方法追加文件
      fd.append('avatar', this.files[0])
//5.ajax发送请求
      axios({
        url: 'http://www.liulongbin.top:3009/api/upload/avatar',
        method: 'post',
        //将FormData对象作为参数,fd对象会自动帮我们设置请求头,自动处理文件参数
        data: fd,
      }).then(res => {
        //成功回调
        console.log(res)
//6.显示上传成功的图片
        document.querySelector('img').src = `http://www.liulongbin.top:3009${res.data.url}`
      })
}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
当使用Spring框架进行文件上传时,可以使用MultipartFile类来处理文件。下面是一个使用MultipartFile上传文件案例: 1. 首先,确保你的项目中已经引入了Spring Web依赖。 2. 创建一个Controller类,用于处理文件上传请求: ```java import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; @Controller public class FileUploadController { @PostMapping("/upload") public String uploadFile(@RequestParam("file") MultipartFile file) { // 处理文件上传逻辑 if (!file.isEmpty()) { try { // 获取文件名 String fileName = file.getOriginalFilename(); // 获取文件内容 byte[] bytes = file.getBytes(); // 执行文件保存操作,例如保存到本地磁盘或者数据库 // ... return "upload_success"; // 返回上传成功页面 } catch (Exception e) { e.printStackTrace(); return "upload_error"; // 返回上传失败页面 } } else { return "upload_error"; // 返回上传失败页面 } } } ``` 3. 在Spring配置文件中配置文件上传的相关配置(可选)。 4. 创建一个HTML表单页面,用于提交文件: ```html <!DOCTYPE html> <html> <head> <title>文件上传示例</title> </head> <body> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" value="上传" /> </form> </body> </html> ``` 以上就是一个使用MultipartFile上传文件的简单案例
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

谢豪杰

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值