图片上传

简单的图片上传功能实现:

这里写图片描述

这里写图片描述


页面JSP:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page contentType="text/html;charset=UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta name="Generator" content="EditPlus">  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>首页</title>
<link rel="stylesheet" type="text/css" href="${ctx }/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="${ctx }/themes/icon.css">


<title></title>
</head>
<body style="background-color: #E1ECFF">
    <div>
            <div>文件上传:</div><br>
            <div>
                <img id="photo" alt="" src="${ctx }/images/1507774341468.jpg" 
                        style="width:200px;height:260px;">
                <br><br>
                <input id="changeFile" type="file"  style="width:200px;height: 30px;" 
                        accept="image/gif,image/jpeg,image/jpg">
            </div>
        </div>
</body>
<script type="text/javascript" src="${ctx }/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="${ctx }/js/jquery.easyui.min.js"></script>
<script type="text/javascript" src="${ctx }/locale/easyui-lang-zh_CN.js"></script>

<script type="text/javascript">
        $(function(){
            var path,clip = $("#photo"),FileReader = window.FileReader;  
            $("#changeFile").change(function() {  
                if (FileReader) {//chrome浏览器处理  
                    var reader = new FileReader(),  
                        file = this.files[0];  
                    reader.onload = function(e) {  
                        clip.attr("src", e.target.result);//这里是把图片转成64位数据存入<img>中的src里  
                    };  
                    reader.readAsDataURL(file);  
                    //这里需要延迟一下,否则无法放入文本框内  
                    setTimeout("showchange()",1000);  
                }  
                else {//其他浏览器处理,火狐在这里就不写出来了,网上资料很多  
                    path = $(this).val();  
                    if (/"\w\W"/.test(path)) {  
                        path = path.slice(1,-1);  
                    }  
                    clip.attr("src",path);  
                }  
            });  

        });  
        //存入照片数据  
        function showchange(){  
            var base64ImageData = $("#photo").attr("src");  
            //获取当前的系统时间
            var time  = new Date().getTime();
            $.ajax({
                url:"${ctx}/account/saveImage.do",
                type:"post",
                data:{"base64ImageData":base64ImageData,"time":time},
                dataType:"json",
                success:function(result){
                    window.parent.$.messager.alert('信息',"保存成功!", "info");
                },
                error:function(){
                    window.parent.$.messager.alert('信息',"请求失败!", "error");
                }
            });
        }  
    </script>
</html>

后端的处理:
后端主要处理了图片,是否保存的问题。将图片转换成转成64位数据,通过ajax传到后台中进行处理。

    @RequestMapping("/saveImage.do")
    @ResponseBody
    public Map<String,String> saveImage() throws Exception{
        HttpServletRequest request = ((ServletRequestAttributes)
                RequestContextHolder.getRequestAttributes()).getRequest(); 
        //获取64位的数据
        String base64ImageData = request.getParameter("base64ImageData");
        //获取当前时间,作为图片的命名
        String time = request.getParameter("time");
        String subStringBase64 = base64ImageData.substring(base64ImageData.indexOf("base64,")+7);

        System.out.println(subStringBase64);

        String path = AccountController.class.getResource("/").getFile().
                replace("WEB-INF/classes/", "").substring(1)+"images/"+time+".jpg";

        System.out.println(path);

         Map<String,String> map = new HashMap<String, String>();
        boolean b = GenerateImage(subStringBase64,path);
        if(b){
            map.put("result", "success");
        }else{
            map.put("result", "error");
        }
        return map;
    }

    // 对字节数组字符串进行Base64解码并生成图片
    public static boolean GenerateImage(String imgStr, String imgFilePath) {
        if (imgStr == null) // 图像数据为空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            // Base64解码
            byte[] bytes = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            // 生成jpeg图片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(bytes);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值