2016-12-07 3 views
0

Я знаю, что есть уже некоторые ответы, но я действительно не понимаю, почему это не работает в моем случае. Ниже мой код для загрузки на удаленном сервере. Я использую phonegap и jquery mobile.Only problem изображение не отображается на странице перед загрузкой на сервер.Предварительный просмотр изображения перед загрузкой в ​​phonegap

<html> 
 
<head> 
 
<title>File Transfer Example</title> 
 
<script type="text/javascript" src="cordova.js"></script> 
 
<script type="text/javascript"> 
 
     
 
function getImage() { 
 
navigator.camera.getPicture(uploadPhoto, function(message) { 
 
alert('get picture failed'); 
 
}, { 
 
quality: 100, 
 
destinationType: navigator.camera.DestinationType.FILE_URI, 
 
sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY 
 
}); 
 
     
 
} 
 

 
function uploadPhoto(imageURI) { 
 
document.getElementById("smallImage").src = imageURI 
 
} 
 
     
 
function uploadPhoto(imageURI) { 
 
     
 
    
 
var options = new FileUploadOptions(); 
 
options.fileKey = "file"; 
 
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1); 
 
options.mimeType = "image/jpeg"; 
 
console.log(options.fileName); 
 
var params = new Object(); 
 
params.value1 = "test"; 
 
params.value2 = "param"; 
 
options.params = params; 
 
options.chunkedMode = false; 
 
     
 

 
var ft = new FileTransfer(); 
 
ft.upload(imageURI, "http://abc.in/my.php", 
 
      
 
function(result){ 
 
console.log(JSON.stringify(result)); 
 
    alert('success'); 
 
}, function(error){ 
 
console.log(JSON.stringify(error)); 
 
}, options); 
 
    
 
} 
 
    
 
     
 
    
 
</script> 
 
</head> 
 
<body> 
 
<button onclick="getImage()">Upload a Photo</button><br> 
 
<img style="width:160px;" id="smallImage" src="" /> 
 
</body> 
 
</html>

ответ

1

The imageURI является псевдо-путь, так что он может быть недоступен на вас локальный HTML-страницы.

Вы можете обновить изображение src после загрузки изображения.

var ft = new FileTransfer(); 
ft.upload(imageURI, "http://abc.in/my.php", 

function(result){ 
    var data = JSON.stringify(result); 
    var imageSrc = data.src; // e.g: "http://abc.in/picture.jpg" 
    document.getElementById("smallImage").src = imageSrc; 
}, 

HTTP-URL должен работать.

+0

Благодаря она работает, но как я делать это каждый раз для новых ulpoaded изображений, так как ее показывает только связанные изображения, я хочу, чтобы отображать изображения, как только я загрузить его на сервер по одному ,пожалуйста помоги –

0

После 3-х дней у меня есть решение по моему запросу, проблема заключается в симуляторе, проверьте ниже код с файлом apk. Не теряйте время на тестировании симулятора. Он не будет просматривать изображение. Ниже код работает для предварительного просмотра изображения перед загрузкой.

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<title>Submit form</title> 
 

 
<script type="text/javascript" charset="utf-8" src="cordova.js"></script> 
 
<script type="text/javascript" charset="utf-8"> 
 

 
var pictureSource; // picture source 
 
var destinationType; // sets the format of returned value 
 

 
// Wait for device API libraries to load 
 
// 
 
document.addEventListener("deviceready",onDeviceReady,false); 
 

 
// device APIs are available 
 
// 
 
function onDeviceReady() { 
 
    pictureSource = navigator.camera.PictureSourceType; 
 
    destinationType = navigator.camera.DestinationType; 
 
} 
 

 

 
// Called when a photo is successfully retrieved 
 
// 
 
function onPhotoURISuccess(imageURI) { 
 

 
    // Show the selected image 
 
    var smallImage = document.getElementById('smallImage'); 
 
    smallImage.style.display = 'block'; 
 
    smallImage.src = imageURI; 
 
} 
 

 

 
    // A button will call this function 
 
    // 
 
function getPhoto() { 
 
    // Retrieve image file location from specified source 
 
    navigator.camera.getPicture(onPhotoURISuccess, onFail, { quality: 50, 
 
    sourceType: navigator.camera.PictureSourceType.PHOTOLIBRARY }); 
 
    } 
 

 
    
 
    function uploadPhoto() { 
 

 
    //selected photo URI is in the src attribute (we set this on getPhoto) 
 
    var imageURI = document.getElementById('smallImage').getAttribute("src"); 
 
    if (!imageURI) { 
 
     alert('Please select an image first.'); 
 
     return; 
 
    } 
 

 
    //set upload options 
 
    var options = new FileUploadOptions(); 
 
    options.fileKey = "file"; 
 
    options.fileName = imageURI.substr(imageURI.lastIndexOf('/')+1); 
 
    options.mimeType = "image/jpeg"; 
 
    options.chunkedMode = false; 
 

 
    options.params = { 
 
     firstname: document.getElementById("firstname").value, 
 
     lastname: document.getElementById("lastname").value 
 
    } 
 

 

 
    options.headers = { 
 
     Connection: "close" 
 
    }; 
 

 
    var ft = new FileTransfer(); 
 
    ft.upload(imageURI, encodeURI("http://abc.in/savepng.php"), win, fail, 
 

 
options); 
 
} 
 

 
// Called if something bad happens. 
 
// 
 
function onFail(message) { 
 
    console.log('Failed because: ' + message);alert('success'); 
 
} 
 

 
function win(r) { 
 
    console.log("Code = " + r.responseCode); 
 
    console.log("Response = " + r.response); 
 
    alert("Response =" + r.response); 
 
    console.log("Sent = " + r.bytesSent); 
 
} 
 

 
function fail(error) { 
 
    alert("An error has occurred: Code = " + error.code); 
 
    console.log("upload error source " + error.source); 
 
    console.log("upload error target " + error.target); 
 
} 
 

 
</script> 
 
</head> 
 
<body> 
 

 
    <button onclick="getPhoto();">Select Photo:</button><br> 
 
    <img style="display:none;width:60px;height:60px;" id="smallImage" src="" /><br> 
 

 
<form id="regform"> 
 
    First Name: <input type="text" id="firstname" name="firstname"><br> 
 
    Last Name: <input type="text" id="lastname" name="lastname"><br> 
 
    <input type="button" id="btnSubmit" value="Submit" onclick="uploadPhoto();"> 
 
</form> 
 
</body> 
 
</html>

Смежные вопросы