2012-01-02 114 views
1

我想將畫布保存到MySQL數據庫(BLOB單元格)中。我有函數在JavaScript在MySQL數據庫中保存畫布

function saveCanvas(){ 
    var canvas = document.getElementById("canvas"); 

    var dataURL = canvas.toDataURL("image/png"); 
    dataURL = dataURL.replace(/^data:image\/(png|jpeg);base64,/, "");  
    var req = $.ajax({ 
     url: "Canvases", 
     type: "Post", 
     data: "operation=0&sessionId=" + readCookie('sessionId') + "&title=" + document.getElementById('imageNameTextbox').value + "&pic=" + dataURL, 
     success: function(){ 
     } 
    }); 
} 

然後我用Java來存儲我的圖片

BASE64Decoder decoder = new BASE64Decoder(); 

byte[] pic = decoder.decodeBuffer(request.getParameter("pic")); 
CanvasController.AddCanvas(sessionId, new CanvasModel(0, 0, request.getParameter("title"), pic)); 

並插入到數據庫:

String insertStatement = "INSERT INTO Canvas(userId, title, pic) VALUES (?, ?, ?);"; 
    prepStmt = connection.prepareStatement(insertStatement); 
    prepStmt.setInt(1, id); 
    prepStmt.setString(2, canvas.getTitle()); 
    prepStmt.setBytes(3, canvas.getPic()); 
    prepStmt.executeUpdate(); 

運行,我總是在數據庫獲取空的圖像後。當我改變圖像/ PNG圖像/ JPEG和借鑑,例如:

http://imageshack.us/photo/my-images/714/pobranec.jpg

我得到:

http://imageshack.us/photo/my-images/15/pobrane2q.jpg

你能告訴我在做什麼錯?

回答

1

您的數據字符串編碼不正確,導致數據在服務器上收到並從郵件正文中提取時出現損壞。更改data這樣:

data: { 
     operation: 0, 
     sessionId: readCookie('sessionId'), 
     title : document.getElementById('imageNameTextbox').value, 
     pic: dataURL 
    } 

,讓jQuery的處理編碼爲您服務。

+0

謝謝,它的工作原理。 – vesper 2012-01-02 20:00:20