Home > Web Front-end > JS Tutorial > body text

How to get local images to display in the browser and upload them to the server in js

零到壹度
Release: 2018-04-21 14:53:17
Original
11007 people have browsed it

The content of this article is about the browser displaying the preview of the local image and calling the back-end interface to upload the image to the server. It has certain reference value. Now I share it with everyone. Friends in need can refer to it. Let’s take a look

1. jsp page

<%@ 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>

        <p id="enteringInfor">

            <form id="uploadForm" >

               <p class="formItem" style="float:left">
                   <p class="itemBlock">
                        <p 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;">
                        </p>
                    </p>
                    <p class="itemBlock">
                         <p 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>
                        </p>
                    </p>
                </p>

                <p class="formItem" style="float:right;margin-top:50px;">
                    <p class="picture">
                        <p class="layui-upload">
                            <p class="layui-upload-list" id="localImag">
                                <img  class="layui-upload-img" id="userPic"   style="max-width:90%" alt="How to get local images to display in the browser and upload them to the server in js" >
                                <p id="demoText"></p>
                            </p>
                            <p 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)"  />
                            </p>
                        </p> 
                     </p>
                </p>

            </form>

            <p 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>
            </p>

            <input type="hidden" name="userId" id="userId"/>
        </p><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;
        $(&#39;#userPic&#39;).viewer({
            url: &#39;src&#39;,
        });
    } 

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

2. Controller interface

/** 
     * 添加用户
     * @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);
        }

    }
Copy after login

3. Tools Category

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;

    }


}
Copy after login

4. Effect
How to get local images to display in the browser and upload them to the server in js

How to get local images to display in the browser and upload them to the server in js

3. After the picture is uploaded successfully, save it to the specified location Under the folder
How to get local images to display in the browser and upload them to the server in js

4. Database data
How to get local images to display in the browser and upload them to the server in js


## related Recommended:

HTML5 Crop the image locally and upload it to the server

Compress the local image and upload it to the server

JAVA uploads files and images to the server and saves them

Insert the WeChat editor article style Upload pictures to WeChat server

The above is the detailed content of How to get local images to display in the browser and upload them to the server in js. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template