Domanda

Sto cercando di implementare NicetIt con il plugin di NICUPLOAD, ma quando selezionando un file da caricare, dice "Impossibile caricare l'immagine" e la risposta del server dice "ID di upload non valido".

Questo è il codice che chiama lo script e inizializza:

<script src="http://js.nicedit.com/nicEdit-latest.js" type="text/javascript"></script>
<script type="text/javascript">//<![CDATA[
bkLib.onDomLoaded(function() {
new nicEditor({uploadURI : '../../nicedit/nicUpload.php'}).panelInstance('area1');
});
//]]>
</script>
.

Il percorso di NICUPLOAD.php è corretto e il codice è quello che può essere trovato nella documentazione: http://nicedit.com/src/nicupload/nicupload.js

Ho fatto modificare la cartella di caricamento e impostare le autorizzazioni di scrittura.Secondo la documentazione ( http://wiki.nicetit.com/w/page/515 / Configurazione% 20Options ), questo è tutto, ma continuo a ricevere errori.Qualche idea?

È stato utile?

Soluzione

Puoi passare manualmente un ID sul tuo script: E.G NICUPLOAD.php? ID= Intropicheader e diventerà Intropicheader.jpg (o estensione appropriata) nella cartella Immagini che hai definito.

Tuttavia, ho notato che questo script è rotto e non riesco ad accedere all'opzione di configurazione Uploaduri se specificata direttamente in NicetIt.js durante il NiceditorAdvancedButton.Extend ({. Questo causa l'accesso a una risorsa "sconosciuta" relativamente positiva, causando un errore .

La documentazione implica diversamente e il fatto che il Nicuri sia stato specificato qui per imgur.com (forse come predefinito) mi ha dato l'impressione che potrei anche aggiungere un riferimento uploaduri allo script di nicupload.php in un unico posto piuttosto che su ogni istanziazione dell'editor.

Aggiornamento

Funziona se lo passa durante l'istanziazione, che immagino consentono una facile popolazione di ID dinamica.

Sfortunatamente, il nicupload.php è pieno di errori e la sua output non è JSON. L'editor prevede di analizzare JSON e trova un tag e gli errori di script con un token inaspettato "<".

Ci sono una zattera di altri errori che tenterò di identificare:

in NicetIt.js

    .
  1. a.append ("immagine") dovrebbe essere infatti a.Append ("NICIMAGE")
  2. questo.onuploaded (d.upload) dovrebbe diventare questo.onuploaded (D)
  3. Questo.Onuploaded (D) deve essere spostato all'interno del blocco Try dopo VAR D= JSON.PARESE (c.Responsetext) per correggere i problemi di ambito variabile
  4. b.image.width deve diventare b.width

    in nicupload.php

      .
    1. L'output JSON non è formato correttamente, commenta l'output HTML e l'output solo JSON_CeCode ($ Stato).
    2. L'output JSON deve restituire una coppia di tasti / valori denominati collegamenti anziché URL, anche se la ridenominazione del VAR D= B.Links a Var D= B.URL in NicetIt.js sarebbe anche sufficiente come una correzione.

      Sia il codice PHP e JavaScript lascia molto da desiderare, ottengo regolarmente molti errori e li sto sistemando.

Altri suggerimenti

Dopo aver cercato una soluzione a lungo (molti post senza soluzione reale), ora ho risolto il codice da solo.Ora sono in grado di caricare un'immagine sul mio server.THX per Firebug ed Eclipse; -)

Il problema principale è che il NICUPLOAD.PHP è vecchio e non funziona con la funzione corrente di caricamento NECKEDIT.

mancante è la gestione degli errori, sentiti libero di aggiungere questo ...

Aggiungi il NeriTitor al file PHP e configurarlo per utilizzare il NicetIt.php:

new nicEditor({iconsPath : 'pics/nicEditorIcons.gif', uploadURI : 'script/nicUpload.php'}
.

Scarica il Nicetit.js Non compresso e modifica le seguenti righe in NicetIt.js:

uploadFile : function() {
var file = this.fileInput.files[0];
if (!file || !file.type.match(/image.*/)) {
  this.onError("Only image files can be uploaded");
  return;
}
this.fileInput.setStyle({ display: 'none' });
this.setProgress(0);

var fd = new FormData(); 
fd.append("image", file);
fd.append("key", "b7ea18a4ecbda8e92203fa4968d10660");
var xhr = new XMLHttpRequest();
xhr.open("POST", this.ne.options.uploadURI || this.nicURI);

xhr.onload = function() {
  try {
    var res = JSON.parse(xhr.responseText);
  } catch(e) {
    return this.onError();
  }
  //this.onUploaded(res.upload); // CHANGE HERE
  this.onUploaded(res);
}.closure(this);
xhr.onerror = this.onError.closure(this);
xhr.upload.onprogress = function(e) {
  this.setProgress(e.loaded / e.total);
}.closure(this);
xhr.send(fd);
.

},

onUploaded : function(options) {
this.removePane();
//var src = options.links.original; // CHANGE HERE
var src = options['url'];
if(!this.im) {
  this.ne.selectedInstance.restoreRng();
  //var tmp = 'javascript:nicImTemp();';
  this.ne.nicCommand("insertImage", src);
  this.im = this.findElm('IMG','src', src);
}
var w = parseInt(this.ne.selectedInstance.elm.getStyle('width'));
if(this.im) {
  this.im.setAttributes({
    src : src,
    width : (w && options.image.width) ? Math.min(w, options.image.width) : ''
  });
}
.

}

Cambia il nicupload.php come questo

<?php
/* NicEdit - Micro Inline WYSIWYG
 * Copyright 2007-2009 Brian Kirchoff
 *
 * NicEdit is distributed under the terms of the MIT license
 * For more information visit http://nicedit.com/
 * Do not remove this copyright message
 *
 * nicUpload Reciever Script PHP Edition
 * @description: Save images uploaded for a users computer to a directory, and
 * return the URL of the image to the client for use in nicEdit
 * @author: Brian Kirchoff <briankircho@gmail.com>
 * @sponsored by: DotConcepts (http://www.dotconcepts.net)
 * @version: 0.9.0
 */

/* 
* @author: Christoph Pahre
* @version: 0.1
* @description: different modification, so that this php file is working with the newest nicEdit.js (needs also modification - @see) 
* @see http://stackoverflow.com/questions/11677128/nicupload-says-invalid-upload-id-cant-make-it-works
*/

define('NICUPLOAD_PATH', '../images/uploadedImages'); // Set the path (relative or absolute) to
                                      // the directory to save image files

define('NICUPLOAD_URI', '../images/uploadedImages');   // Set the URL (relative or absolute) to
                                      // the directory defined above

$nicupload_allowed_extensions = array('jpg','jpeg','png','gif','bmp');

if(!function_exists('json_encode')) {
    die('{"error" : "Image upload host does not have the required dependicies (json_encode/decode)"}');
}

if($_SERVER['REQUEST_METHOD']=='POST') { // Upload is complete

    $file = $_FILES['image'];
    $image = $file['tmp_name'];
    $id = $file['name'];

    $max_upload_size = ini_max_upload_size();
    if(!$file) {
        nicupload_error('Must be less than '.bytes_to_readable($max_upload_size));
    }

    $ext = strtolower(substr(strrchr($file['name'], '.'), 1));
    @$size = getimagesize($image);
    if(!$size || !in_array($ext, $nicupload_allowed_extensions)) {
        nicupload_error('Invalid image file, must be a valid image less than '.bytes_to_readable($max_upload_size));
    }

    $filename = $id;
    $path = NICUPLOAD_PATH.'/'.$filename;

    if(!move_uploaded_file($image, $path)) {
        nicupload_error('Server error, failed to move file');
    }

    $status = array();
    $status['done'] = 1;
    $status['width'] = $size[0];
    $rp = realpath($path);
    $status['url'] =  NICUPLOAD_URI ."/".$id;


    nicupload_output($status, false);
    exit;
} 

// UTILITY FUNCTIONS

function nicupload_error($msg) {
    echo nicupload_output(array('error' => $msg)); 
}

function nicupload_output($status, $showLoadingMsg = false) {
    $script = json_encode($status);
    $script = str_replace("\\/", '/', $script);
    echo $script;

    exit;
}

function ini_max_upload_size() {
    $post_size = ini_get('post_max_size');
    $upload_size = ini_get('upload_max_filesize');
    if(!$post_size) $post_size = '8M';
    if(!$upload_size) $upload_size = '2M';

    return min( ini_bytes_from_string($post_size), ini_bytes_from_string($upload_size) );
}

function ini_bytes_from_string($val) {
    $val = trim($val);
    $last = strtolower($val[strlen($val)-1]);
    switch($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
        case 'm':
            $val *= 1024;
        case 'k':
            $val *= 1024;
    }
    return $val;
}

function bytes_to_readable( $bytes ) {
    if ($bytes<=0)
        return '0 Byte';

    $convention=1000; //[1000->10^x|1024->2^x]
    $s=array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB');
    $e=floor(log($bytes,$convention));
    return round($bytes/pow($convention,$e),2).' '.$s[$e];
}

?>
.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top