简单的图片上传

在任何一个项目中,不管是前台页面还是后台管理,图片上传都是一个必不可少的地方。尽管如此,在刚开始需要用到图片上传的时候,是根本不会写。我第一次写的时候,不知道怎么写?也不知道怎么上传?更不知道上传到什么地方?前不久,写出来了一个上传的方法,只是一个简单的图片上传。

1.前台页面选择图片和显示图片

<div class="form-group">
            <div class="col-sm-2">

            </div>
            <div class="col-sm-10" style="width: 20%; margin-left: 50px">
                <div id="preview" style="width: 150px;height:150px;border:1px solid gray;">
                </div>
                <div class="file" style="z-index: 999;margin-left: 30px">选择图片
                    <input type="file" name="file" id="pic">
                </div>
            </div>
        </div>

2.图片的样式及其CSS代码

<style>
    .file {
        position: relative;
        display: inline-block;
        background: #D0EEFF;
        border: 1px solid #99D3F5;
        border-radius: 4px;
        padding: 4px 12px;
        overflow: hidden;
        color: #1E88C7;
        text-decoration: none;
        text-indent: 0;
        line-height: 20px;
    }

    .file input {
        position: absolute;
        font-size: 100px;
        right: 0;
        top: 0;
        opacity: 0;
    }

    .file:hover {
        background: #AADFFD;
        border-color: #78C3F3;
        color: #004974;
        text-decoration: none;
    }

    #preview {
        width: 150px;
        height: 150px;
        overflow: hidden;
    }

    #preview img {
        width: 100%;
        height: 100%;
    }
</style>

3.运行html页展示如下界面


4.输入框对应的点击事件,(点击选择图片之后,图片会显示在div中,展示图片)

$('[type=file]').change(function (e) {                                             获取点击的input框,添加修改事件
            var file = e.target.files[0]                                           得到输入框中的内容,并定义给一个变量
            preview1(file)                                                         并执行preview1方法
        })
function preview1(file) {
        haveImg = true;
        var img = new Image(), url = img.src = URL.createObjectURL(file)            把定义的值传到这个方法中,并转化成图片
        var $img = $(img)
        img.onload = function () {
            URL.revokeObjectURL(url)
            $('#preview').empty().append($img);                                     并在id为preview的div中显示图片
        }
    }
5.在下方添加一个保存按钮(在按钮的点击方法中执行下面这个方法)
function uploadFile() {
        var pic = $("#pic").get(0).files[0];                                      获取input中存入的值(此处为图片的另一种格式)
        var formData = new FormData();                                            定义一个formdata表单,并把得到的值存到表单中
        formData.append("file", pic);
        $.ajax({                                                                  此处为ajax请求,(请求的url下面会给出)
            type: "POST",
            url: htturl+"uploadImage1",
            data: formData,
            async: false,
            processData: false, //必须false才会自动加上正确的Content-Type
            dataType: 'json',
            contentType: false,//必须false才会避开jQuery对 formdata 的默认处理
            success: function (res) {
                picc = res.data;
            },
            error: function (xhr, textStatus) {
                ShowFailure('错误,上传失败')
                console.log(xhr)
                console.log(textStatus)
            }

        });

    }
6.后端接口书写
@RequestMapping(value="/uploadImage1",method= RequestMethod.POST)                             请求的接口对应的url
    public HttpResponseEntity upload(@RequestBody MultipartFile file, HttpServletRequest request) throws IOException {
        HttpResponseEntity httpResponseEntity = new HttpResponseEntity();
        try {
            String path = request.getSession().getServletContext().getRealPath("upload");      图片存放的位置,会存放在项目中,自动生成一个文件夹为upload
                String fileName = file.getOriginalFilename();//                                获取到上传文件的名字
                String suffix = fileName.substring(fileName.lastIndexOf('.'));                 把获取到的图片名字按'.'截取,(此处获取图片的格式)
                String newfileName = UUIDUtil.getOneUUID()+suffix;                             自动生成一个64位的uuid,和图片的格式拼接得到一个新的字符串
                System.out.println(newfileName);
                File dir = new File(path,newfileName);                                         并把生成的图片存到upload文件夹下
                if(!dir.getParentFile().exists()){
                    dir.getParentFile().mkdirs();
                }
                                                                                               //MultipartFile自带的解析方法
                file.transferTo(dir);                                                           
                httpResponseEntity.setCode(Constans.SUCCESS_CODE);
                httpResponseEntity.setData(newfileName)                                       会把图片重新生成名字返回到前台,再通过字符串的拼接就可以显示新上传的图片
             httpResponseEntity.setMessage("图片上传成功");
} catch (Exception e) { httpResponseEntity.setCode(Constans.INSERT_PIC_ERROR_MESSAGE); httpResponseEntity.setMessage("图片上传失败"); } return httpResponseEntity; }7.刷新工程,在工程下的upload文件夹中会出现上传的图片

如果出现的图片,那就说明上传成功了,此时再通过img标签进行拼接字符串们就可以显示上传的图片了。此方法只是简单的上传图片,而且还是存放到项目中,如果图片过多,就不要这么写了,就应该把图片上传到服务器了。

猜你喜欢

转载自blog.csdn.net/qq_39776207/article/details/80249075