2013-06-26 3 views
2

Я использую эту функцию:JQuery/javascript: как получить значение входного файла?

function resize(file, max_width, max_height, compression_ratio, imageEncoding){ 
    var fileLoader = new FileReader(), 
    canvas = document.createElement('canvas'), 
    context = null, 
    imageObj = new Image(), 
    blob = null; 

    //create a hidden canvas object we can use to create the new resized image data 
    canvas.id  = "hiddenCanvas"; 
    canvas.width = max_width; 
    canvas.height = max_height; 
    canvas.style.visibility = "hidden"; 
    document.body.appendChild(canvas); 

    //get the context to use 
    context = canvas.getContext('2d'); 

    // check for an image then 
    //trigger the file loader to get the data from the image 
    if (file.type.match('image.*')) { 
     fileLoader.readAsDataURL(file); 
    } else { 
     alert('File is not an image' + file); 
    } 

    // setup the file loader onload function 
    // once the file loader has the data it passes it to the 
    // image object which, once the image has loaded, 
    // triggers the images onload function 
    fileLoader.onload = function() { 
     var data = this.result; 
     imageObj.src = data; 
    }; 

    fileLoader.onabort = function() { 
     alert("The upload was aborted."); 
    }; 

    fileLoader.onerror = function() { 
     alert("An error occured while reading the file."); 
    }; 


    // set up the images onload function which clears the hidden canvas context, 
    // draws the new image then gets the blob data from it 
    imageObj.onload = function() { 

     // Check for empty images 
     if(this.width == 0 || this.height == 0){ 
      alert('Image is empty'); 
     } else { 

      context.clearRect(0,0,max_width,max_height); 
      context.drawImage(imageObj, 0, 0, this.width, this.height, 0, 0, max_width, max_height); 


      //dataURItoBlob function available here: 
      // http://stackoverflow.com/questions/12168909/blob-from-dataurl 
      blob = dataURItoBlob(canvas.toDataURL(imageEncoding)); 

      //pass this blob to your upload function 
      $("#imgcaptmobile").append('<img id="imagecaptmobile" src="' + blob + '" >'); 
     } 
    }; 

    imageObj.onabort = function() { 
     alert("Image load was aborted."); 
    }; 

    imageObj.onerror = function() { 
     alert("An error occured while loading image."); 
    }; 

} 

С помощью этого HTML кода:

<input type=\"text\" name=\"form_titre_photo_capture_mobile\" placeholder=\"Titre\" class=\"texte_texte_photo_capture_mobile\" id=\"form_titre_photo_capture_mobile\"> 
          <input type=\"file\" capture=\"camera\" accept=\"image/*\" id=\"takePictureField\" name=\"takePictureField\"> 
          <canvas id=\"canvas_captimg\" width=\"487\" height=\"365\"></canvas> 
          <div id=\"imgcaptmobile\" style=\"display:hidden\"></div> 

Я не могу получить "файл" вар выполнить функцию! Я tryied это:

$('#takePictureField').change(function(e) { 
    var file = $(this).val(); 
    console.log($(this).val()); 
    resize(file, 487, 800, 70, "image/jpeg"); 
}); 

Но ошибка на бревне консоли является: '. Изображения * «неперехваченного TypeError не удается вызвать метод„матч“неопределенный» (при вызове, если (file.type.match ()) {) Так что я предполагаю, что я не называю значение входного файла правильно? ...

ответ

2

это потому, что val возвращает объект строки, имя выбранного файла, а не file объекта, что ваш код ожидает его , вам необходимо использовать files property:

$('#takePictureField').change(function(e) { 
    var file = this.files; // this.files[0] => the first selected file object 
    resize(file, 487, 800, 70, "image/jpeg"); 
}); 
+0

Я изменил его. Теперь в консоли у меня есть «FileList {0: File, length: 1, item: function}» и такая же ошибка: Uncaught TypeError: Не удается вызвать метод «match» undefined – Recif

+0

Редактировать: я положил [0], и он похоже, получает файл. Но у меня все еще есть ошибка после: Uncaught ReferenceError: dataURItoBlob не определен – Recif

+0

@Recif Вам следует передать первый выбранный файл-объект 'this.files [0]'. Ваша функция не выполняет итерацию в коллекции 'fileList'. – undefined

0

Аналогичная проблема. Я решил это. При таком подходе JQ возвращает массив, и вы можете получить любое значение, namefile например:

uploadFieldHolder.on('change', function(e){ 
    var file = this.files; 
    console.log(file[0]['name']); 
}); 
//It returns somefile.jpg