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