java上传图片,把图片存到本地

思路:js通过FileReader获取图片的Base64,Java解码用IO存到本地。

 

HTML 代码

<input type="file"  ng-model="form.product_img_url" name="uploadifyfile" id="good_uploadifyfile" />

 

JavaScript

        var objFile = document.getElementById("good_uploadifyfile").files[0];
                    console.log("type: " + objFile.type.split("/")[1]);
                    if(!/image\/\w+/.test(objFile.type)){ 
                        alert("看清楚,这个需要图片!"); 
                        return false; 
                    } 
                
                    //console.log(objFile.size); // 文件字节数
                    
                    var reader = new FileReader(); 
                    //将文件以Data URL形式读入页面 
                    reader.readAsDataURL(objFile); 
                    reader.onload=function(e){ 
                        //console.log("result: " + this.result);
                        //var result=document.getElementById("good_result"); 
                        //显示文件 
                        //result.innerHTML='<img src="' + this.result +'" alt="" />';
                        $("#good_result img").attr("src", this.result);
                        $("#good_result img").show();
                        //$scope.form.imgBase64 = this.result;
                        $scope.form.imgType = objFile.type.split("/")[1];
                    } 
                }

 

Java

//base64字符串转化成图片
    public static String GenerateImage(String imgStr,String pk,HttpServletRequest request)
    {   
        System.out.print("已经收到了把字节码转化为图片的方法");
        //对字节数组字符串进行Base64解码并生成图片
        if (imgStr == null) //图像数据为空
            return "error";
        
        //解析base64码,获取图片格式
        String str [] = imgStr.split(",");
        imgStr = str[1];
        String imgInfo = str[0];
        String imgExt = imgInfo.split("/")[1].split(";")[0];
        
        BASE64Decoder decoder = new BASE64Decoder();
        try
        {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for(int i=0;i<b.length;++i)
            {
                if(b[i]<0)
                {//调整异常数据
                    b[i]+=256;
                }
            }
            String imgFilePath = "/SCApp/images/"+pk+"."+imgExt;//新生成的图片
            System.out.println(imgFilePath);
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return imgExt;
        }
        catch (Exception e)
        {
            return "error";
        }
    }

 

转载于:https://www.cnblogs.com/remember-forget/p/9597851.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值