文件上传时按钮美化碰到的问题


前言

最近做项目,用到了文件上传,但是<input type="file">自带的样式实在是太丑了,于是就想着封装一下选择文件的样式。
常用的样式有三种,楼主一一尝试了,但是会有一些bug,这里记录一下碰到的问题。


一、文件上传按钮的三种样式

此处是参考了别人的写法:

<!--html结构-->
<!--第一种方法:通过定位+透明度来实现(不推荐)-->
<div class="first">
    第一种方法
    <button>上传图片</button>
    <input type="file">
</div>
 
/*css代码*/
/*第一种的按钮样式*/
.first{
    position: relative;
    height: 30px;
    line-height: 30px;
}
.first button,.first input{
    position: absolute;
    left: 85px;
    top: 0;
    width: 100px;
    height: 30px;
    color: #fff;
    background-color: skyblue;
    border-radius: 5px;
    border: none;
    outline: none;
    cursor: pointer;
}
.first input{
    opacity: 0;
    width: 185px;
    left: 0;/*这里是为了让cursor效果在按钮内完全生效,但是弊端就是宽度增加,在按钮左侧看不见的位置也能点击到*/
}
<!--html结构-->
<!--第二种方法:通过label的关联属性来实现-->
<div class="item">
    第二种方法
    <label for="file1">上传图片</label>
    <input type="file" id="file1">
</div>
 
/*css代码*/
/*第二种的按钮样式*/
.item label{
    display: inline-block;
    width: 100px;
    height: 30px;
    text-align: center;
    color: #fff;
    line-height: 30px;
    background-color: skyblue;
    border-radius: 5px;
    cursor: pointer;
}
.item input{
    display: none;
}
<!--html结构-->
<!--第三种方法:通过js事件绑定来实现(推荐)-->
<div class="item">
    第三种方法
    <button class="btn">上传图片</button>
    <input type="file" id="file">
</div>
 
/*css代码*/
/*第三种的按钮样式*/
.item button{
    width: 100px;
    height: 30px;
    color: #fff;
    background-color: skyblue;
    border-radius: 5px;
    border: none;
    outline: none;
    cursor: pointer;
}
.item input{
    display: none;
}
 
// js代码
// 第三种方法
document.querySelector('.btn').addEventListener('click',function () {
    document.querySelector('#file').click();
});

上面三种方法的样式都是一样的,如图:
图片描述
在这里插入图片描述

二、碰到的问题

以上三种文件上传按钮的方法都可以用,我最开始用的是第三种的方式,前台是使用AJAX封装的FormData来进行文件上传,但是后台接收文件的时候,一直提示为空。反复寻找也没找到原因,经过测试,只是知道了第三种方式在form表单中选择完文件不显示文件名,但是直接使用form表单提交的方式,是可以进行文件上传的。
经过多次测试,我果断选择了第二种方式,接下来就是代码。

1. html

代码如下(示例):

<style>
        .item label{
            width: 8%;
            height: 40px;
            text-align: center;
            color: #fff;
            background-color: #314690;
            border-radius: 5px;
            cursor: pointer;
            padding: 8px;
            font-size: 18px;
        }
        .item input{
            display: none;
        }
    </style>

 <div style="margin-top: 10px;" class="item"> 
         <label for="file">本地上传</label>
         <input type="file" id="file" name="file">
 </div>
 function save(){
  var formData = new FormData($("#form")[0]);
            $.ajax({
                type: "post",
                url: "./uploadFile.do",
                data: formData,
                cache: false,
                processData: false,
                contentType: false,
                dataType: "json",
                sync: false,
                success: function (data) {
                    alert(data.msg);
                }
            })
 }

2. java

代码如下(示例):

package com.banxia.utils;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;


//图片上传
@Controller
public class UploadFileController {

    @RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
    @ResponseBody
    //  anjularJS上传文件的话,需要指定这个属性  @RequestParam(value = "file")
    public Map<String, String> uploadPhoto(MultipartFile file, HttpServletRequest request) {
        Map<String, String> ret = new HashMap<>();
        if (file == null) {
            ret.put("type", "error");
            ret.put("msg", "选择要上传的文件!");
            return ret;
        }
        if (file.getSize() ==0) {
            ret.put("type", "error");
            ret.put("msg", "请先选择文件!");
            return ret;
        }
        if (file.getSize() > 1024 * 1024 * 20) {
            ret.put("type", "error");
            ret.put("msg", "文件大小不能超过20M!");
            return ret;
        }
        //获取文件后缀
        String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf(".") + 1);
        if (!"doc,docx,txt".toUpperCase().contains(suffix.toUpperCase())) {
            ret.put("type", "error");
            ret.put("msg", "请选择doc,docx,txt格式的文件!");
            return ret;
        }
        //获取项目根目录加上图片目录 webapp/static/imgages/upload/
        String savePath = request.getSession().getServletContext().getRealPath("/") + "/file/";
        File savePathFile = new File(savePath);
        if (!savePathFile.exists()) {
            //若不存在该目录,则创建目录
            savePathFile.mkdir();
        }
        String filename = new Date().getTime() + "." + suffix;
        try {
            //将文件保存指定目录
            file.transferTo(new File(savePath + filename));
        } catch (Exception e) {
            ret.put("type", "error");
            ret.put("msg", "保存文件异常!");
            e.printStackTrace();
            return ret;
        }
        ret.put("type", "success");
        ret.put("msg", "论文上传成功!");
        //返回给前端的路径    "filepath":"/file/"
        ret.put("filepath", request.getSession().getServletContext().getContextPath() + "/file/");
        ret.put("filename", filename);
        return ret;
    }
}

总结

一点前端小问题耽误了我好久,看来还真的是需要好好补一下前端的知识了,总算是解决了,简单记录一下笔记。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值