2017-03-03 72 views
0

上傳圖像到服務器,圖像是從,然後我想通過ajax,服務器端使用python燒瓶框架,圖像到服務器發佈圖像,它需要base64編碼格式,問題是我怎麼能使用JavaScript將圖像轉換爲base64格式。後base64編碼圖像到服務器使用javascript

\t $('.img-upload-btn').click(function(event) { 
 
\t \t $("#img-upload").click(); 
 
\t }); 
 

 
\t $('#img-upload').on('change', function(event) { 
 
\t \t event.preventDefault(); 
 
\t \t var img = $("#img-upload")[0].files[0]; 
 
\t \t console.log(toDataUrl(img.name)); 
 

 
\t \t var img_data = { 
 
\t \t \t "spec_id": 212, 
 
\t \t \t "file": img 
 
\t \t }; 
 
\t \t console.log(img); 
 
\t \t $.ajax({ 
 
\t \t \t url: 'http://10.0.0.75:5000/api/check_specification', 
 
\t \t \t type: 'POST', 
 
\t \t \t dataType: 'json', 
 
\t \t \t contentType: "application/json; charset=utf-8", 
 
\t \t \t success: function(data) { 
 
\t \t \t \t alert(data); 
 
\t \t \t }, 
 

 
\t \t \t failure:function(errorMsg) { 
 
\t \t \t \t alert(errorMsg); 
 
\t \t \t } 
 
\t \t }); 
 
\t \t 
 
\t });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<button class="btn-search full-width img-upload-btn">upload-img</button> 
 
<input type="file" id="img-upload" >

+0

的可能的複製[你怎麼可以編碼在JavaScript字符串爲Base64?](http://stackoverflow.com/questions/246801/how-can-you-encode-a-string-to-base64 -in-javascript) –

回答

2

像這樣的東西,你可以用base64得到的圖像。

fileChange(e) { 
    /* any way to get the object input */ 
    var file = document.querySelector('input[type=file]'); 
    let reader = new FileReader(); 
    if(file.files[0]) { 
     reader.onload =() => { 
     imgBase64 = reader.result; 
     console.log(reader.result); 
     //your request 
     } 
     reader.readAsDataURL(file[0]); 
    } 
} 
+0

你的回答是正確的! – flypan

相關問題