Springboot+Ajax上传并预览头像

一.效果:

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

二.前端代码:

1.表单上加上enctype="multipart/form-data",表示此表单上传包含文件.

2.img显示并预览上传的头像,input上传头像控件,type="file"

 <div class="row cl">
   	<label class="form-label col-xs-4 col-sm-3">头像:</label>
   	<div class="formControls col-xs-8 col-sm-9">
   			<img id="head_picture" style="width:50px;height:50px;border-radius:50%" src=""/>
   			<span class="btn-upload form-group formControls" style="margin-top: 10px;">
   					<a style="margin-left:10px;" class="btn btn-secondary radius">更换头像</a>
						<input type="file" id="head_picture_file" name="file" class="input-file">
   			 </span>
		</div>
</div>

上传按钮样式修改css

.btn-upload {
    position: relative;
    display: inline-block;
    height: 31px;
    *display: inline;
    overflow: hidden;
    vertical-align: middle;
    cursor: pointer
}

.input-file {
    position: absolute;
    right: 0;
    top: 0;
    cursor: pointer;
    z-index: 1;
    font-size: 30em;
    opacity: 0;
    filter: alpha(opacity=0)
}

3.利用js预览上传的图片

//预览上传的头像
    $("#head_picture_file").change(function (e) {
        var reader = new FileReader();
        file = e.target.files[0];
        if (!/image\/\w+/.test(file.type)) {//判断文件的是不是图片
            alert("上传的文件格式不对,请重新上传...");
            return false;
        }
        reader.readAsDataURL(file);
        reader.onload = function (e) {
            $("#head_picture").attr("src", "" + this.result + "");
        };
    });

4.ajax上传带文件的表单

var formData = new FormData($("#update_user_form")[0]); //封装表单数据
    formData.append("name", name);//额外的表单数据
    formData.append("sessionId",sessionId)
    $.ajax({
        url: URL + '/api/admin/user/' + id,
        type: 'PUT',
        data: formData,
        cache : false,
        contentType : false, //必需,因为我们在表单上填加了`enctype="multipart/form-data"`,所以这里设为false
        processData : false,//必需,默认为true,发送的数据转为Object,适合于"application/x-www-form-urlencoded",这里设为false
        xhrFields: {
            withCredentials: true //跨域请求必须
        },
        success: function (result) {
            
        }
    });

后端代码:

0.导入pom文件:

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.2.2</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

1.方法的形参中:@RequestParam(value = "file", required = false) MultipartFile file,我们上传了文件file对象就会存在而不是为空.

2.将MultipartFile对象存在项目的静态目录下,我存在C:\src\idea\SDJUBBS\src\main\resources\static\common\images\avatar

 public static String saveFile(MultipartFile filedata, String pathval) {
        File fileDir = new File(pathval);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        // 上传的文件名
        String filename = System.currentTimeMillis() + "_" + filedata.getOriginalFilename();
        // 总的文件路径
        String filePath = pathval + "/" + filename;
        File file = new File(System.getProperty("user.dir") + "/" + filePath);
        try {
            FileOutputStream out = new FileOutputStream(file);
            // 写入文件
            out.write(filedata.getBytes());
            out.flush();
            out.close();
            return filePath;// 返回图片保存路径
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}

将上传的文件保存在服务器,然后将照片的路径返回即可.

注意:这里有个问题也是很多人遇到不知道如何解决的:上传文件到项目中,项目中确实也看到了上传的文件,可前端访问文件就是404,需要重启项目,才能访问的到.

解决办法:

造成这种现象的原因是tomcat服务器对静态资源的一种保护措施,你访问的虚拟路径没有映射到实际的位置,需要自己配置.

package com.selenium.sdjubbs.common.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
public class ResourceConfig extends WebMvcConfigurerAdapter {
    @Autowired
private SdjubbsSetting setting;
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //前面是映射后的地址,后面是需要映射的地址
        //获取文件的真实路径
        String path = System.getProperty("user.dir") + setting.getBaseDirSavePath();
        //映射到/static/common/下的所有文件
        registry.addResourceHandler("/common/**").
        addResourceLocations("file:" + path);
        super.addResourceHandlers(registry);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Selenium399

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

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

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

打赏作者

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

抵扣说明:

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

余额充值