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";
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM