js获取本地图片显示到浏览器并上传至服务器_Bronna的博客-程序员宅基地

技术标签: 上传图片  浏览器  javaweb  数据库  

浏览器显示本地图片的预览图,调用后端接口将图片上传至服务器

一、jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <META HTTP-EQUIV="pragma" CONTENT="no-cache"> 
        <META HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate"> 
        <META HTTP-EQUIV="expires" CONTENT="0">
        <!-- 引入js -->
        <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery.js"></script>
        <script type="text/javascript" src="<%=request.getContextPath()%>/js/jquery.min.js"></script>
    <body>

        <div id="enteringInfor">

            <form id="uploadForm" >

               <div class="formItem" style="float:left">
                   <div class="itemBlock">
                        <div style="display:inline-block;float:left" class="selectContainer">
                            <span class="txtBox">姓名</span>
                            <input type="text" class="select"  name="realName" id="realName"  placeholder="请输入姓名" style="width:200px;">
                        </div>
                    </div>
                    <div class="itemBlock">
                         <div style="display:inline-block;float:left" class="selectContainer">
                            <span class="txtBox">性别</span>
                            <select class="select" name="gender" id="gender" >
                                <option value="1"></option>
                                <option value="2"></option>
                            </select>
                        </div>
                    </div>
                </div>

                <div class="formItem" style="float:right;margin-top:50px;">
                    <div class="picture">
                        <div class="layui-upload">
                            <div class="layui-upload-list" id="localImag">
                                <img class="layui-upload-img" id="userPic" style="width:330px;height:410px">
                                <p id="demoText"></p>
                            </div>
                            <div class="btn btn-primary fileinput-button"  style="width:332px;position:absolute;bottom:0px">
                                <span class="uploadTxt">上传图片</span>
                                <input class="form-control layui-btn" id="entrustPicUpload" type="file" name="entImg" onchange="getPhoto(this)"  />
                            </div>
                        </div> 
                     </div>
                </div>

            </form>

            <div class="modelEditorBottom" style="padding-left:24px;text-align:center;height:70px;line-height:70px;border:none;width:100%;overflow:hidden;zoom:1">
                <button class="buttons adminButton" onclick="saveUser()">保存</button>
            </div>

            <input type="hidden" name="userId" id="userId"/>
        </div>
<script>
    var imgurl = "";  
    function getPhoto(node) {
       
        var imgURL = "";  
        try{  
            var file = null;  
            if(node.files && node.files[0] ){  
                file = node.files[0];  
            }else if(node.files && node.files.item(0)) {  
                file = node.files.item(0);  
            }  
            //Firefox 因安全性问题已无法直接通过input[file].value 获取完整的文件路径  
            try{  
                imgURL =  file.getAsDataURL();  
            }catch(e){  
                imgRUL = window.URL.createObjectURL(file);  
            }  
        }catch(e){  
            if (node.files && node.files[0]) {  
                var reader = new FileReader();  
                reader.onload = function (e) {
       
                    imgURL = e.target.result;  
                };  
                reader.readAsDataURL(node.files[0]);  
            }  
        }
        creatImg(imgRUL);//显示图片
        return imgURL;  
    }  
    function creatImg(imgRUL){
       
        document.getElementById("userPic").src = imgRUL;
        $('#userPic').viewer({
            url: 'data-original',
        });
    } 

    //保存
    function saveUser(){
     
        //数据判断
        var realName=$("#realName").val();
        if(realName==null||realName==''){
            layer.msg('用户名不能为空!',{icon : 7,time:1000});
            return ;
        }
        var imgSrc = $("#userPic").attr("src");
        if(imgSrc == "" || imgSrc==null){
            layer.msg('请上传图片!',{icon : 7,time:1000});
            return ;
        }
        var formData = new FormData($("#uploadForm")[0]);
        $.ajax({  
            url : "../addUser",  
            type: 'POST',  
            data: formData,  
            async: false,  
            cache: false,  
            contentType: false,  
            processData: false, 
            success : function(data) {
     
                var obj =  JSON.parse(data);
                layer.msg('保存成功!', {icon : 6,time : 2000});
            },  
            error : function(data) {
       
                layer.msg('保存失败!', {icon : 5,time : 2000});
            }
        }); 
    }
    </script>
    </body>

</html>

二、controller接口

/** 
     * 添加用户
     * @param session
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping(value = "/addUser", method = RequestMethod.POST)
    public void addUser(MultipartFile entImg,HttpSession session, HttpServletRequest request, HttpServletResponse response)
            throws IOException {
        String realName = request.getParameter("realName");//姓名
        String gender = request.getParameter("gender");// 性别

        //调用工具类上传图片
        String userPic = FileUtils.uploadUser(entImg, request);

        TestUser testUser = new TestUser();
        testUser.setRealName(realName);
        testUser.setGender(Integer.parseInt(gender));
        testUser.setUserPic(userPic);

        // 添加人员信息及图片url到数据库
        int res= userService.insertUser(testUser);
        if (res > 0) {
            writeJSON(response, res);
        } else {
            writeJSON(response,null);
        }

    }

三、工具类

public class FileUtils {
    

    FILES_PATH("files_path"); // 此路径存放于jdbc.properties配置文件中,例如:files_path=D:/uploadImgs
    private static final String path = PropertiesUtil.get(FILES_PATH)+"/user";

    /**
     * 上传图片URL
     * @param fileName
     * @param request
     * @return
     */
    public static String getPath(String fileName,HttpServletRequest request) {
        String ip=IpUtil.getIP();
        int port=request.getLocalPort();
        StringBuilder sb=new StringBuilder();
        sb.append("http://");
        sb.append(ip);
        sb.append(":");
        sb.append(port);
        sb.append("/uploadImgs/user/");
        sb.append(fileName);
        return sb.toString();
    }


    /**
     * 以时间戳对上传文件进行重新命名
     * @param file
     * @return
     */
    public static String renameFile(MultipartFile file) {
        if(file!=null) {
            Long date=new Date().getTime();
            String fileRealName=file.getOriginalFilename();
            String prefix=fileRealName.substring(fileRealName.lastIndexOf(".")+1);
            String fileName = date.toString()+"."+prefix;  
            return fileName;
        }
        return null;
    }

    /**
     * 图片上传
     * @param file
     * @param fileName
     */
    public static String uploadUser(MultipartFile file, HttpServletRequest request) {

        // 重命名
        String renameFile = FileUtils.renameFile(file);
        // 图片名
        String picPath = FileUtils.getPath(renameFile, request);
        // 上传
        File targetFile = new File(borpath, renameFile);
        if (!targetFile.exists() && !targetFile.isDirectory()) {
            targetFile.mkdirs();
        }
        try {
            file.transferTo(targetFile);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return picPath;

    }


}

四、效果
这里写图片描述

这里写图片描述

3.图片上传成功后保存至指定文件夹下
这里写图片描述

4.数据库数据
这里写图片描述

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/bronna/article/details/80026539

智能推荐

validatebox ajax验证,validateBox(验证框) - jQuery EasyUI中文文档 - EasyUI中文站_凯鹅的博客-程序员宅基地

ValidateBox(验证框)使用$.fn.validatebox.defaults重写默认值对象。validatebox(验证框)的设计目的是为了验证输入的表单字段是否有效。如果用户输入了无效的值,它将会更改输入框的背景颜色,并且显示警告图标和提示信息。该验证框可以结合form(表单)插件并防止表单重复提交。通过标签创建验证框。使用Javascript创建验证框。$('#vv').valida..._validatebox 重写

Vue+ECharts的小示例_单页vue+echarts-程序员宅基地

Vue+ECharts做数据可视化1. VueVue 是一套用于构建用户界面的渐进式框架。与其它大型框架不同的是,Vue 被设计为可以自底向上逐层应用。Vue 的核心库只关注视图层,不仅易于上手,还便于与第三方库或既有项目整合。另一方面,当与现代化的工具链以及各种支持类库结合使用时,Vue 也完全能够为复杂的单页应用提供驱动。我使用的Vue版本是3.11.0。2.EChartshttps://echarts.apache.org/examples/zh/index.htmlECharts的所有示_单页vue+echarts

概览屏幕_UltimateSMS的博客-程序员宅基地

概览屏幕(也称为最新动态屏幕、最近任务列表或最近使用的应用)是一个系统级别 UI,其中列出了最近访问过的 Activity 和任务。用户可以浏览该列表并选择要恢复的任务,也可以通过滑动清除任务将其从列表中移除。对于 Android 5.0 版本(API 级别 21),包含不同文档的同一 Activity 的多个实例可能会以任务的形式显示在概览屏幕中。例如,Google Drive 可能对多...

VMware虚拟机安装Linux系统(详细版)_段远山的博客-程序员宅基地

所谓虚拟机(virtual machine),就是通过软件技术虚拟出来的一台计算机,它在使用层面和真实的计算机并没有什么区别。常见的虚拟机软件有VMware Workstation(简称 VMware)、VirtualBox、Microsoft Virtual PC 等,其中 VMware 市场占有率最高,所以本节以VMware为例来讲解 Linux 的安装。VMware 可以使你在一台计算机上同时运行多个操作系统,例如同时运行 Windows、Linux 和 Mac OS。在计算机上直接安...

搜索引擎:检索技巧(Google谷歌,百度)+ 常用的资源网站及技巧_从google,百度或其他你熟悉的搜索引擎中搜索出相关的网站,并浏览其内容,将你_橙子味儿的芒果的博客-程序员宅基地

基本上都是基于Google(谷歌)的检索技巧,但有些技巧也可用于其他搜索引擎,如百度,搜狗等1、如图 2、常用网站及技巧 "indexof/"格式名即可搜索到可下载的资源 技巧九:搜索Google Directory  Google在它的搜索数据库中将成千上万的网页索引化——这就能使得不会产生压倒性数量的搜索结果。量确实已经够了,但有时你也许..._从google,百度或其他你熟悉的搜索引擎中搜索出相关的网站,并浏览其内容,将你

centos卸载openjdk_Tomorrow_Yesterday的博客-程序员宅基地

先查看 rpm -qa | grep java 显示如下信息: java-1.4.2-gcj-compat-1.4.2.0-40jpp.115 java-1.6.0-openjdk-1.6.0.0-1.7.b09.el5 卸载: rpm -e --nodeps java-1.4.2-gcj-compat-1.4.2.0-40jpp.115 rpm -e --nodeps jav...

随便推点

相机相册OC 详解_oc 相册管理_William-logical的博客-程序员宅基地

最近不是很忙,写一些博客希望对初学者有所帮助_oc 相册管理

Ubuntu 安装openoffice_刘易君的博客-程序员宅基地

文档地址:http://orangered3stones.iteye.com/blog/1496611http://www.lampdeveloper.co.uk/linux/converting-doc-to-pdf-txt-or-html-using-php-and-linux.html环境:Ubuntu Server 11.04 64位,OpenJDK 6, OpenOffice...

Ubuntu fcitx CPU占用率很高解决方法_极客字节的博客-程序员宅基地

Ubuntu fcitx CPU占用率很高解决方法 在Ubuntu中,有时候电脑的风扇突然狂装,用 pidstat -u 5 1 命令查看后台应用的资源占用情况,发现fcitx的占用率接近百分之百。原因是搜狗云输入的问题,关闭后,在用kill命令干掉这个进程,风扇就不转了,以后使用也不会再出现这种情况。步骤:1.在应用目录里找到 Fic..._崩溃 fcitx cpu高负载

HR吐槽程序员:约30个面试的因下雨都没来!网友:你们公司太差劲_因为下雨天不来面试的人_白帽子技术分享的博客-程序员宅基地

我们每一个人都想有一份好工作,比如希望工作地点离家近,工资高等等这些优点。但是这样的工作往往可遇不可求,需要运气和实力都具备,才能找到这样的工作。因此我们在求职的时候一般都是面试多家公司,然后从职业发展、薪资待遇、员工福利等多方面考虑,然后择优选择!按理说想要有一个好工作,就需要了解公司,而通过网络渠道了解的话,似乎有点片面。因此对于面试者来说,每一个企业都要“实地考察”,然后和公司..._因为下雨天不来面试的人

oracle进程命令的6571(Linux Error: 13: Permission denied)_congshi5914的博客-程序员宅基地

今天遇到了一个很郁闷的小问题。当时为了进行数据库的升级备份了product文件夹,当进行product恢复的时候发现:以oracle用户启动数据库,其可以以sid或者net service name的方式登陆数据库,而其他属...

度盘又有大变动:充不充会员差距更大了_程序员小乐的博客-程序员宅基地

点击上方 "编程技术圈"关注,星标或置顶一起成长后台回复“大礼包”有惊喜礼包!每日英文Instead of giving yourself reasons why you...

推荐文章

热门文章

相关标签