头像上传-前后端分离

背景:表单提交,将用户的头像传递到后台,后台通过流处理,将文件写到文件服务器(本地模拟)并存入数据库

效果图:

前端:

html中需要引入

  • jquery-3.4.1.min.js
  • jquery.form.js
<div class="ui container" id="upload">
        <!--enctype="multipart/form-data"表示表单有多种数据构成,既有文本,又有二进制-->
        <form id="dataForm" class="ui form" enctype="multipart/form-data" method="post"
              action="http://localhost:9527/user/uploadfile">
            <div class="field inp">
                <label>用户名:</label>
                <!--这里踩过一个坑 不能用disabled 用那个的话往后台传,username为null-->
                <input id="username" type="text" name="username" readonly>
            </div>
            <div class="field">
                <label>头像:</label>
                <!--为了把cookie携带过去 ajaxForm提交没办法携带cookie 值通过js赋-->
                <input id="cookies" type="text" name="cookies" hidden>
                <input id="file" type="file" name="file">
            </div>
            <div style="text-align: center;margin: 30px 0 150px 0">
                <!--type必须为submit-->
                <button class="ui blue button" id="confirm" type="submit">确定</button>
            </div>
        </form>
    </div>

相应的js代码:

var username=window.localStorage.getItem('username');
    $('#username').val(username);
    //document.cookie获取到所有的cookie
    $('#cookies').val(document.cookie);
    //上传头像
    $('#dataForm').ajaxForm(function (data) {
        if (data.code === 2000) {
            window.location.reload()
        } else {
            alert(data.message)
        }
    })

后端:

 @Value("${filePath}")  //具体值在配置文件application.yml中
    private String filePath;

/**
     * 头像上传
     * @param username 指定用户
     * @param file 传入的文件
     * @param cookie
     * @return
     * @throws IOException
     */
public ResultVO uploadFile(String username, MultipartFile file, String cookie) throws IOException {
        //获取到文件名称
        String fileName = file.getOriginalFilename();
        //获取到文件全路径
        String path=filePath+ File.separator+fileName;
//1.将文件通过IO写到filePath(用本机模拟文件服务器),注意FileOutputStream()中必须得是具体文件
        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(path));
        try {
            bos.write(file.getBytes());
            bos.flush();
        } catch (IOException e) {
            e.printStackTrace();
            throw new IOException(ApiResponseCodeEnum.NO_USER.getMessage());
        }finally {
            bos.close();
        }
        //2.存入数据库中
        User user=userMapper.getByUsername(username);
        if (user == null){
            return ResultVO.fail(ApiResponseCodeEnum.NO_USER.getCode(),
                    ApiResponseCodeEnum.NO_USER.getMessage());
        }
        user.setImageUrl("../static/img/" +fileName);
        if (cookie == null){
            new File(path).delete();
            return ResultVO.fail();
        }else {
            String[] cookiesArr = cookie.split(";");
            //我在cookie中存的是{name:token+UUID,value:UUID}
            for (String temp : cookiesArr) {
                if (temp.contains("token")) {
                    String[] split = temp.split("=");//前端传来的是"tokenUUID=UUID"字符串
                    redisUtil.set(split[1], user);//redis存的是{key:UUID,value:user}
                    return ResultVO.success();
                }
            }
        }
        //更新数据库
        int i = userMapper.updateByPrimaryKeySelective(user);
        if (i == 0){
            //删除文件
            new File(path).delete();
            return ResultVO.fail(ApiResponseCodeEnum.FAIL_UPLOAD.getCode(),
                    ApiResponseCodeEnum.FAIL_UPLOAD.getMessage());
        }
        return ResultVO.success();
    }

其中,filePah是在yml中进行的配置,这里存在了项目的img中

filePath: F:\workspace_webstorm\shop_web\static\img

结尾:我写的不清楚的地方我们可以交流,希望对你有所帮助,也期望指出问题。共同进步~

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值