Primero, tomemos las representaciones:
Este es el código que hice para más fotos en ese momento. Lo sacaré para que aprendas (algunos lugares deben ser modificados por sus propias personalidades, y la dirección general es correcta)
Hay tres documentos involucrados en total (regularmente hablando)
1.Rutee Entry File (I Am /Routes.js aquí, y a menudo está en /app.js)
La copia del código es la siguiente:
// Agregar comida deliciosa
app.all ('/add', users.add);
2. Archivo del controlador de operación (yo soy /routes/users.js aquí)
La copia del código es la siguiente:
// Agregar comida deliciosa
exports.add = function (req, res) {
if (req.method == "get") {
Var user = {};
if (req.session.user) {
usuario = req.session.user;
}
res.render ("Uss/Food_add", {Título: 'Release Food-'+config.name, name: config.name, user: user});
} else if (req.method == "post") {
// Obtener datos
var x = req.body.x;
var y = req.body.y;
var cat_id = req.body.cat_id;
var cat_name = req.body.cat_name;
dirección var = req.body.address;
VAR Title = req.body.title;
var desc = req.body.desc;
var content = req.body.content;
var pics = '';
VAR Price = req.body.price;
var tags = req.body.tags;
var add_time = date.parse (nueva fecha ())/1000;
soporte var = 0;
var uid = req.body.uid;
// Procesamiento de imágenes de imagen
//console.dir(req.files);
var file_obj = req.files.pics;
//console.log(file_obj.length);
var file_obj2 = [];
for (var i = 0; i <file_obj.length; i ++) {
if (file_obj [i] .name) {
file_obj2.push (file_obj [i]);
}
}
var longitud = file_obj2.length;
if (longitud> 0) {
file_obj2.forEach (function (item, index) {
if (item.path) {
var tmppath = item.path;
var type = item.type;
var extension_name = "";
// Muévase al directorio especificado y generalmente lo ponga en el archivo de imágenes públicas
// asegúrese de que la ruta ya exista cuando se mueva, de lo contrario se informará un error
var tmp_name = (date.Parse (nueva fecha ())/1000);
tmp_name = tmp_name+''+(math.round (math.random ()*9999));
// juzga el tipo de archivo
Switch (tipo) {
caso 'Image/PJPeg': Extension_Name = 'JPG';
romper;
caso 'Image/jpeg': extension_name = 'jpg';
romper;
caso 'Image/GIF': Extension_Name = 'GIF';
romper;
caso 'Image/Png': Extension_Name = 'Png';
romper;
caso 'Image/X-Png': Extension_Name = 'Png';
romper;
caso 'Image/BMP': Extension_Name = 'BMP';
romper;
}
var tmp_name = tmp_name+'.'+extension_name;
var TargetPath = 'public/images/' + tmp_name;
console.log (tmppath);
// Mueve el archivo temporal cargado al directorio especificado
Fs.Rename (tmppath, targetPath, function (err) {
if (err) {
tirar err;
}
if (fotos) {
Pics += ',' +tmp_name;
}demás{
fotos += tmp_name;
}
// juzga si se completa
//console.log(index);
// Eliminar archivos temporales
fs.unlink (tmppath, function () {
if (err) {
tirar err;
}demás{
if ((index+1) == longitud) {
console.log (TargetPath);
// se completa el procesamiento de carga
//datos
var data = {
x: x, // longitud
y: y, // dimensión
CAT_ID: CAT_ID, // ID de categoría
CAT_NAME: CAT_NAME, // Nombre de la categoría
Dirección: dirección, // dirección
Título: Título, // Título
DESC: DESC, // INTRODUCCIÓN
Contenido: Contenido, // Contenido
Fotos: fotos, // campo de imágenes, separan múltiples imágenes con ','
Precio: precio, // precio
Etiquetas: etiquetas, // Las etiquetas están separadas por ','
add_time: add_time, // admite
Soporte: Soporte, // El soporte predeterminado es 0
uid: uid // La identificación de usuario puede ser anónima
};
Food_predao.insert (datos, funciones (err, alimentos) {
if (err) {
res.json ({err: 100, contenido: 'error de base de datos'});
}demás{
res.json ({err: 0, contenido: '¡Liberar exitoso!', Data: Food});
}
});
}
}
});
});
}
});
}demás{
// sin fotos
//datos
var data = {
x: x, // longitud
y: y, // dimensión
CAT_ID: CAT_ID, // ID de categoría
CAT_NAME: CAT_NAME, // Nombre de la categoría
Dirección: dirección, // dirección
Título: Título, // Título
DESC: DESC, // INTRODUCCIÓN
Contenido: Contenido, // Contenido
Fotos: fotos, // campo de imágenes, separan múltiples imágenes con ','
Precio: precio, // precio
Etiquetas: etiquetas, // Las etiquetas están separadas por ','
add_time: add_time, // admite
Soporte: Soporte, // El soporte predeterminado es 0
uid: uid // La identificación de usuario puede ser anónima
};
Food_predao.insert (datos, funciones (err, alimentos) {
if (err) {
res.json ({err: 100, contenido: 'error de base de datos'});
}demás{
res.json ({err: 0, contenido: '¡Liberar exitoso!', Data: Food});
}
});
}
}
};
3. Ver archivo (soy /views/users/food_add.ejs aquí)
La copia del código es la siguiente:
<estilo>
.Upload_item {ancho: 50px; Altura: 45px; desbordamiento: oculto; borde: 2px discontinuo #bfbfbf; flotante: izquierda; margen-derecha: 10px;}
.upload_item_add {ancho: 50px; Altura: 45px; Pantalla: bloque; Línea-aguja: 42px; Text-Align: Center; tamaño de fuente: 30px; cursor: puntero;}
.upload_input {}
</style>
<script>
var add = {
upload_click: function (obj) {
$ (obj) .parent (). Children (). Eq (1) .Click ();
},
upload_change: function (obj) {
ruta var;
ruta = $ (obj) .val (); // c:/documentos y configuración/hud/escritorio/addfile.jpg
var aa;
aa = path.split ('.');
//alert(AAAAa.length-1]); // resultado JPG
nombre var;
name = path.split ('//');
var bb = name [name.length-1];
// alerta (bb.substr (0, bb.indexof ('.'))); // Resultado de addfile
$ (obj) .parent (). Children (). Eq (0) .CSS ('FontSize', '12px');
$ (obj) .parent (). CSS ('Borderstyle', 'Solid');
$ (obj) .parent (). Children (). Eq (0) .html (bb.substr (0, bb.indexof ('.')));
if ($ (obj) .parent (). attr ('index') == 1) {// Agregar nuevo
var html = '<div index = "1"> <span onClick = "add.upload_click (this)">+</span> <input type = "file" name = "Pics" id = "Pics" onchange = "add.upload_change (this)"/> </div>';
$ ('#upload_box'). append (html);
$ (obj) .parent (). attr ('índice', '0');
}
}
};
</script>
<Form Method = "Post" Action = "/Add" Enctype = "Multipart/Form-Data">
<Table>
<tr>
<TD> longitud: </td> <td> <input type = "text" name = "x" id = "x"/> </td>
</tr>
<tr>
<td> dimensión: </td> <td> <input type = "text" name = "y" id = "y"/> </td>
</tr>
<tr>
<TD> Categoría: </td> <td> <select name = "cat_id"> <opción valor = "1"> Categoría 1 </opción> </select> </td>
</tr>
<tr>
<TD> Dirección: </td> <td> <input type = "text" name = "dirección" id = "dirección"/> </td>
</tr>
<tr>
<TD> Título: </td> <td> <input type = "text" name = "title" id = "title"/> </td>
</tr>
<tr>
<TD> INTRODUCCIÓN: </td> <td> <input type = "text" name = "Desc" id = "Desc"/> </td>
</tr>
<tr>
<TD> Content: </td> <td> <input type = "text" name = "content" id = "content"/> </td>
</tr>
<tr>
<TD> imagen: </td> <td id = "upload_box"> <div index = "0" style = "display: none;"> <span onClick = "add.upload_click (this)">+</span> <input type = "file" name = "pics" id = "pics" onchange = "add.upload_change (this)"/> <divs> <divic/"Índice". onClick = "add.upload_click (this)">+</span> <input type = "file" name = "Pics" id = "Pics" onChange = "add.upload_change (this)"/> </div> </td>
</tr>
<tr>
<td> precio: </td> <td> <input type = "text" name = "precio" id = "precio"/> </td>
</tr>
<tr>
<td> etiquetas: </td> <td> <input type = "text" name = "tags" id = "tags"/> </td>
</tr>
<tr>
<td colspan = "2"> <input type = "Subt" valor = "enviar" /> </td>
</tr>
</table>
</form>