图片上传 (保存在指定路径)

图片上传 (保存在指定路径)

效果如下:

准备工作:

1) 前端 html

<div class="avatar_inner_content">
    <div>
        头像照片
        <div id="upload_avatar_btn">
            <input class="avatar_upload_input" type="file" placeholder="">选择您要上传的头像
        </div>
        <p class="upload_avatar_tip">支持jpg,jpeg,png格式,且图片小于1M</p>
        <div class="upload_avatar_div"></div>
        <div class="file_upload_tip"></div>
        <div id="upload_avatar_confirm" class="btn">确认</div>
    </div>
</div>

2) 按钮样式

#upload_avatar_btn {
    display: inline-block;
    height: 35px;
    line-height: 35px;
    width: 17%;
    position: relative;
    border: 1px black solid;
    text-align: center;
    margin-left: 2%;
    padding: 2px 2%;
}
.avatar_upload_input {
    width: 100%;
    height: 100%;
    left: 0;
    position: absolute;
    cursor: pointer;
    opacity: 0;
    z-index: 1;
}

图片上传 前端:

1.检测图片合法性

//检测图片合法性
function check_file(file){
    let file_size = file[0].size;           //容量检测
    if(file_size > global_file_size){
        file_upload_tip.text("上传的文件不大于1M");
        return false;
    }
    let file_name = file[0].name;
    if(file_name.lastIndexOf('.') === -1){  //后缀检测
        file_upload_tip.text("后缀名错误");
        return false;
    }
    let suffix = file_name.substr(file_name.lastIndexOf('.') + 1, file_name.length );
    let suffix_reg = /^jpg|jpeg|png|JPG|JPEG|PNG$/;
    if (!suffix_reg.test(suffix)) {
        file_upload_tip.text("图片类型必须是jpg,jpeg,png中的一种");
        return false;
    }
    return true;
}

2.图片选择后直接回显 (尚未上传)

let avatar_upload_input = $(".avatar_upload_input");
let upload_avatar_div = $(".upload_avatar_div");
let avatar_pic_img = $("#avatar_pic_img");
avatar_upload_input.change(function(){
    let file = this.files;
    if(check_file(file) === false){
        $(this).val("");
        return;
    }
    let this_input = $(this);
    let reader = new FileReader();
    reader.readAsDataURL(file[0]);
    reader.onload = function (e) {
        upload_avatar_div.css("background-image", "url(" + e.target.result + ")");
        file_upload_tip.text("");
    }
});

3.图片上传 (ajax)

function doUpload(file_obj) {
    if(file_obj == null){
        return;
    }
    var FileController = "/util/upload.html";     // 接收上传文件的后台地址
    // FormData 对象
    var form = new FormData();
    form.append("file",file_obj);
    // XMLHttpRequest 对象
    var xhr = new XMLHttpRequest();
    //为请求添加返回处理函数
    xhr.onreadystatechange=function () {
        if(this.readyState === 4 && this.status === 200){
            var b = this.responseText;
            if(b === "fail"){
                alert("上传失败");
            }else if(b === "none_user"){
                location.href = "/";
            }
        }
    };
    xhr.open("post", FileController, true);
    xhr.send(form);
}


let avatar_pic_img = $("#avatar_pic_img");
$("#upload_avatar_confirm").click(function(){
    if(typeof(avatar_upload_input[0].files[0]) === "undefined"){
        return;
    }
    doUpload(avatar_upload_input[0].files[0]);
    let reader = new FileReader();
    reader.readAsDataURL(avatar_upload_input[0].files[0]);
    reader.onload = function (e) {
        //右上角头像回显
        avatar_pic_img.css("background-image", "url(" + e.target.result + ")");
    }
});

图片上传 后台:

1.注册外部文件 (保存在非项目目录要做这步, 保存在项目路径可以跳过此步骤)

/**
 * Created by Alwen
 * 2018/11/09 11:31
 * 图片路径配置
 */
@Configuration
@Slf4j
public class WebAppConfig implements WebMvcConfigurer {
    // 获取配置文件中图片的路径
    @Value("${upload.file.path}")
    private String filePath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 访问图片路径
        registry.addResourceHandler("/upload_file/**").addResourceLocations("file:" + filePath);    //注册外部文件
    }
}

2.配置文件属性

@Configuration
public class FileUploadConfig {
    //设置文件maxSize
    @Bean
    public MultipartConfigElement multipartConfigElement(
            @Value("${multipart.maxFileSize}") String maxFileSize,
            @Value("${multipart.maxRequestSize}") String maxRequestSize) {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        // 单个文件最大
        factory.setMaxFileSize(maxFileSize);
        // 设置总上传数据总大小
        factory.setMaxRequestSize(maxRequestSize);
        return factory.createMultipartConfig();
    }
}

3.后台接收 ajax请求

    @Value("${upload.file.path}")
    private String filePath;

    @PostMapping("/upload.html")
    @ResponseBody
    public String upload(HttpSession session, @RequestParam("file") MultipartFile file,
                         @RequestParam("file_type") Integer fileType, @RequestParam("owner_type") Integer ownerType) {
        User sessionUser = (User) session.getAttribute(Constants.SESSION_USER);
        if (sessionUser == null) {
            return "none_user";
        }
        String path = filePath;
        Long fileSize = file.getSize();
        String fileName = file.getOriginalFilename();                                //文件名 + 后缀
        String realName = fileName.substring(0, fileName.lastIndexOf('.'));     //文件名
        String suffix = fileName.substring(fileName.lastIndexOf('.') + 1);      //文件后缀
        String virtualName = UUID.randomUUID().toString();                           //随机文件名(保存在服务器防止重名覆盖)
        log.info("realName: " + realName + " ; suffix: " + suffix + " ; fileType: " + fileType + " ; ownerType: " + ownerType + " ; fileSize: " + fileSize);

        File targetFile = new File(path);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        String url = path + virtualName + "." + suffix;
        log.info("url: " + url);
        File saveFile = new File(url);
        // 保存
        try {
            //保存文件到服务器
            file.transferTo(saveFile);             
            return "success";
        } catch (Exception e) {
            e.printStackTrace();
            return "fail";
        }
    }

附录:

1.数据库设计

Field        Type          Collation        Null    Key     Default  Extra           Privileges                       Comment                          
-----------  ------------  ---------------  ------  ------  -------  --------------  -------------------------------  ---------------------------------
id           int(10)       (NULL)           NO      PRI     (NULL)   auto_increment  select,insert,update,references                                   
file_type    int(10)       (NULL)           YES             (NULL)                   select,insert,update,references  1.身份证(正) 2.身份证(反)
file_size    bigint(20)    (NULL)           YES             (NULL)                   select,insert,update,references  文件大小                     
real_name    varchar(100)  utf8_general_ci  YES             (NULL)                   select,insert,update,references  文件真名                     
file_uri     varchar(255)  utf8_general_ci  YES             (NULL)                   select,insert,update,references  文件路径                     
create_date  datetime      (NULL)           YES             (NULL)                   select,insert,update,references                                   
owner_id     int(10)       (NULL)           YES             (NULL)                   select,insert,update,references    

2.备注: UUID只是为了防止服务器上的文件重名, 数据库中只保存文件真名, 通过id查询

  • 6
    点赞
  • 34
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值