1. Recursos de importación
2. Código JSP
<viv> <label> <span>*</span> Nombre del proyecto: </selete> <div> <input type = "text" value = "$ {proname}" placeholder = "" id = "" name = "proname" readonly = "readonly"> </aw> </iv> <iv> <label -<label> thumbnail: </label> <div> <div id = "filepicker"> seleccionar imagen </div> <botón id = "btn-star"> inicio cargar </boton> </div> </div> </div> <div> <belebel> <span>*</span> Project Invoice Carga: </selt> <div> <div> <div> <div> <div> <d id = "dndarea"> <div = "filepicker-2" "<biv> </div> <biv> <biv> <1/" Div Id = "Id =" Id = "Id =" Filepicker 2 "" <p> o arrastre la foto aquí, puede seleccionar hasta 300 fotos en una sola vez </p> </div> </div> <div style = "display: none;"> <div> <span> 0%</span> <span> </span> </div> <div> <div> <div> <div> iD = "filepicker2"> </div> <iv> star </div> </div> </div> </div> <div> <button onClick = "artículo_add ('', 'Invoicevo/save? & ProjectId = $ {ProjectId} & InvoicesCan =', '10001');" type = "Button"> <i> </i> Save </boton> </div> </div> </div> 3. Código JS
<script type = "text/javaScript"> var imagePath = null; function artículo_save () {alerta ("La capa de bala se cerrará automáticamente al actualizar el padre"); window.parent.location.reload (); } /*Project Incoice-ADD* / function Artículo_add (Título, URL, W, H) {if (ImagePath) {var index = layer.open ({type: 2, title: title, content: url+imagePath}); capa.full (índice); } else {alerta ("Sin carga de imagen, por favor cargue la imagen primero");}} $ (function () {$ ('. Skin-Minimal Enume'). ICheck ({CheckBoxClass: 'iCheckbox-Blue', RadioClass: 'IrAdio-Blue', AgraseArea: '20%'}); $ list = $ ("#filelist"), $ btnn). $ ("#btn-star"), state = "pendiendo", uploader; Servidor de recepción de archivos. 'gif, jpg, jpeg, bmp, png', mimetypes: 'image/*'}}); '</div>' + '<p> Espere ... </p>' + '</div>'), $ img = $ li.find ('img'); src) {if (error) {$ img.replacewith ('<span> no se puede ver </span>'); {var $ li = $ ('#' + file.id), $ porcentaje = $ li .find ('. Progress-box .sr-only'); $ li.find (". State"). Text ("Subiendo"); file.id) .AddClass ('upload-success') .find (". State"). Text ("cargado"); error ");}); // Después de completar la carga, es exitosa o fallida, elimine la barra de progreso primero. uploader.on ('uploadComplete', function (file) {$ ('#' + file.id) .find ('. progress-box'). 'Subir'; $ btn.on ('click', function () {if (state === 'cargar') {uploader.stop ();} else {ifoader.upload ();}}); (función ($) {// Inicialización se inicia cuando DomReady {var $ wrap = $ ('. uploader-list-container'), // contenedor de imágenes $ queue = $ ('<ul> </ul>'). appendTo ($ wrap.find ('. Queuelist'), // Barra de estado, incluyendo progreso y botón de control $ estatusbar = $ wrap.find (''. información. 0, / optimizar retina, en Retina, este valor es 2 relación = window.devicepixelratio || Si el navegador es compatible con la imagen base64 isPpportBase64 = (function () {var data = new image (); var support = true; data.onload = data.onerror = function () {if (this.width! = 1 || this.height! = 1) {Soport = false;}} data.src = "Datos: Image/GIF; Base64, R0LGODLHAQABAIAAAAAAAP /// YWAAAAAAQABAAACAUWAOW =="; Versión.Description; SupportTransition = (function () {var s = document.createElement ('P'). Style, R = 'Transition' en S || 'WebKitTransition' en S || 'MozTransition' en S || 'Mstransition' en S || 'OTransition' en S; s = Null; regreso r;}), // (! Webuploader.uploader.support ('flash') && webuploader.browser.ie) {// flash está instalada pero la versión es demasiado baja if (flashversion) {(function (contenedor) {window ['expressInstallCallcall'] = function (state) {state) {download 'download. Case 'Descargar. (Webuploader.browser.ie) {html + = 'classid = "clsid: d27cdb6e-ae6d-11cf-96b8-4445535400000000"'; name = "wmode" value = "transparent" /> ' +' <param name = "wmode" value = "transparent" /> ' +' <param name = "wmode" value = "transparent" /> ' +' <param name = "wmode" value = "transparent" /> ' +' <param name = "wmode" valor = "transparente" /> ' +' <<mam name " valor = "siempre"/> ' +' </objeto> '; src = "http://www.adobe.com/macromedia/style_guide/images/160x41_get_flash_player.jpg"/> </a> '); // Instanciado uploader = webuploader.create ({pick: {id: '#filepicker-2', etiqueta: 'haga clic para seleccionar imagen'}, formdata: {uid: 123}, dnd: '#dndarea', pegar: '#uploader', swf: 'lib/webuploader/0.1.5/up. up.sweft', chowings: chowing: chowing: chowing: chowles.swf ', choTer. False, Chunksize: 512 * 1024, servidor: 'Invoicevo/News_upploder? & ProjectId = $ {ProjectId}', // runtimeOrder: 'flash', // acepta: {// title: 'Images', // extensions: 'gif, jpg, jpeg, bmp, png', // mimetypes: 'image/ * //////////1S disco Función de arrastre global. uploader.on ('dndaccept', function (items) {var denedy = false, len = items.length, i = 0, // modifique js type sin eLlowed = 'text/sencillo; application/javascript'; for (; i <len; i ++) {// si en la lista (~ no alcaludado.indexof (elementos [i] .type) ! negado;}); //}); { var $li = $('<li id="' + file.id + '">' + '<p>' + file.name + '</p>' + '<p></p>' + '<p><span></span></p>' + '</li>'), $btns = $( '<div>' + '<span>Delete</span>' + '<span>Rotate to the right</span>' + '<span> gire a la izquierda </span> </div>') .AppendTo ($ li), $ prgresres = $ li .find ('p.progress span'), $ wrap = $ li .find ('p.imgwrap'), $ info = $ ('<p> </p>'), ducha = function (código) {cambio (código) {case 'excsese_size': '' size '': '' '' '': '' '' '' ':' '' '': ''. Break; por ejemplo .makethumb (archivo, function (error, src) {var img; if (error) {$ wrap.text ('no puedo presente vista previa'); return;} if (isSupportBase64) {img = $ ('<iMg src = "'+src+'">' '); $ wrap.empty (). append (img);} st ($. 'lib/webuploader/0.1.5/server/preview.php', {método: 'post', data: src, datatype: 'json'}) .Done (function (respuesta) {if (respuesta.result) {img = $ ('<img src = "+respuesta.result+"> "); $ wrap.). {$ Wrap .Text ("Error de vista previa"); else if (prevureciente = '' cola ') {$ li.off (' Mouseenter MouseLeave '); === 'Interruption') {$ info.remove (); $ btns.stop (). Animate ({Height: 30}); por ejemplo, RemoveFile (File); '-o-transform': DEG, 'transformar': DEG}); Responsable de la destrucción de la función de vista (archivo) {var $ li = $ ('#' + file.id); porcentaje; updateTatus (); {text = 'cargar exitoso' + stats.successnum + 'foto a xx álbum,' + stats.uploadfailnum + 'La carga de fotos falló, <a href = "#" rel = "nofollow" rang "rel =" externo externo "> reupload </a> imagen fallida o <a href =" rel = "externo nofollow" rel = "externa externo" }} else {stats = uploader.getStats (); } $ info.html (text); $ queue.hide (); $ statement.removeclass ('Element-Invisible'); Break; por ejemplo, logro.tats (); = $ li .find ('. $ PLACE.AddClass ('Element-Invisible'); removerfile (archivo); == "Error") alerta (respuesta.Error); }); (state === 'Pause') {uploader.upload (); }); }) (jQuery); </script> Aviso:
4. Código del controlador
/** * Salta a la página donde se cargue la factura * @param proname * @param map * @return */@RequestMapping (valor = "/upload") public String InvoiceUpload (String Proname, Long Id, Map <String, Object> Map) {map.put ("proname", proname); ProjectService.getProject (id); map.put ("ProjectId", id); return "Project/InvoiceUpload"; }/** * cargue la factura y guarde la base de datos * @param archivo * @param reference * @param Respuesta * @return */@ResponseBody @RequestMapping (valor = "/news_uploder", método = {requestmethod.post, requestmethod.get}, produce = "aplicación/json; charset = utf-8") Public jsonObjecter (@Requester (@Requester (@ReQueter (@Requestar (@requestar File MultipartFile [], Long ProjectId, HttpServletRequest solicitud, respuesta httpservletResponse) {string flag = null; JsonObject jsonObject = new JsonObject (); Pruebe {webuploaderutil webuploaderUtil = new WebupPloaderUtil (); webuploaderUtil.upload (archivo [0], "cargar/invoice/", solicitud); flag = webuploaderUtil.getFileName (); jsonObject.put ("FilePath", bandera); jsonObject.put ("estado", "éxito"); } catch (Exception e) {E.PrintStackTrace (); } return jsonObject; } 5. Paquete de clase de herramientas com.softjx.util;/** *Nombre del proyecto: qdlimap *Nombre del archivo: webuploaderutil.java *Nombre del paquete: com.ltmap.platform.cms.util *Fecha: 13 de abril de 2017 a las 6:30:45 PM *Copyright (c) 2017,[email protected]. */ import java.io.file; import java.text.simpledateFormat; import java.util.date; import javax.servlet.http.httpservletRequest; importar org.springframework.web.multipart.multipartfile; /** *Título: Webuploaderutil <br/> *Descripción: *@Company: Litu Hi-Tech <br/> *@Autor: liu yunsheng *@versión: v1.0 *@desde: jdk 1.8.0_40 *@fecha: 13 de abril de 2017 a las 6:30:45 pm <br/> */public class Webploaderutil {Private String {Private String permite a Uffixxxxxxxxxxxxx. "JPG, PNG, GIF, JPEG"; // Permitir formato de archivo Private Long - 2l; // Permitir el tamaño de la cadena de tamaño de archivo FileName; cadena privada [] nombres de archivo; public String getAlowSuffix () {return lowuffix; } public void setAlowsUffix (String lowingUfFix) {this.allowsuffix = lowingUfX; } public Long Long getAlowsize () {return lo permite*1024*1024; } public void setAlowsize (Long lo permite) {this.allowsize = wakeize; } public String getFileName () {return FileName; } public void setFileName (string filename) {this.fileName = filename; } public String [] getFileNames () {return FileNames; } public void setFileNames (String [] FileNames) {this.FileNames = FileNames; } / ** * * @title: getFilenameNew * @Description: toDo * @param: @return * @return: string * @author: liu yunsheng * @date: 14 de abril de 2017 a las 10:17:35 am * @throws * / string privado getFileNaMeNew () SimpleDateFormat ("yyyymmddhhmmsssss"); return fmt.format (nueva fecha ()); } / ** * * @title: subidas * @Description: toDo * @param: @param archivos * @param: @param destdir * @param: @param request * @param: @throws excepción * @return: void * @author: liu yUnsheng * @Date: 14 de abril de 2017 a las 10:17:14 estoy Supars (archivos multipartfile [], string Destdir, httpservletRequest solicitud) lanza la excepción {String Path = request.getContextPath (); String basepath = request.getScheme ()+": //"+request.getServerName ()+":"+request.getServerPort ()+ruta; intente {filenames = new String [files.length]; int index = 0; for (archivo multipartfile: archivos) {String sufrejando = file.getOriginalFileName (). Substring (file.getOriginalFileName (). LastIndexOf (".")+1); int longitud = getallowsuffix (). indexOf (sufijo); if (longitud == -1) {tirar nueva excepción ("Cargue el archivo en el formato permitido"); } if (file.getSize ()> getAllowsize ()) {Throw New Exception ("El tamaño del archivo que cargó está fuera de rango"); } String realPath = request.getSession (). GetServletContext (). GetRealPath ("/"); Archivo DestFile = nuevo archivo (RealPath+DestDir); if (! DestFile.Exists ()) {DestFile.mkDir (); } Cadena filenAmEnw = getFileNAmEnw ()+"."+Sufix; // archivo f = nuevo archivo (destfile.getabsolutefile ()+"//"+filenamenew); file.transferto (f); F.CreateNewFile (); nombres de archivo [índice ++] = basepath+destdir+filenamenew; }} Catch (Exception e) {Throw E; }} / ** * * @title: upload * @Description: toDo * @param: @param archivo * @param: @param destdir * @param: @param request * @param: @throws excepción * @return: void * @author: liu yUnsheng * @Date: 14 de abril de 2017 a las 10:16:16 am AM AM AM AM AM AM AM AM AM AM AM * Archivo, String DestDir, HttpservletRequest solicitud) lanza la excepción {String Path = request.getContextPath (); // http: // localhost: 8088/huahang string basepath = request.getScheme ()+": //"+request.getServerName ()+":"+request.getServerPort ()+rath; Pruebe {String sufix = file.getOriginalFileName (). Substring (file.getOriginalFileName (). LastIndexOf (".")+1); int longitud = getallowsuffix (). indexOf (sufijo); if (longitud == -1) {arrojar una nueva excepción ("Por favor, cargue archivos en el formato permitido"); } if (file.getSize ()> getAllowsize ()) {Throw New Exception ("El tamaño del archivo que cargó ha excedido el rango"); } String realPath = request.getSession (). GetServletContext (). GetRealPath ("/")+"/"; Archivo DestFile = nuevo archivo (RealPath+DestDir); if (! DestFile.Exists ()) {destfile.mkdirs (); } String FileNAmEnw = getFileNAmEnw ()+"."+Sufijo; Archivo f = nuevo archivo (destfile.getabsolutefile ()+"/"+filenamenew); file.transferto (f); F.CreateNewFile (); // Incluya la ruta completa del sitio web http: // localhost: 8080/qdlimap/upload/user/20170414104142667.png // filename = basepath+destdir+filenamenew; // devuelve la ruta relativa de carga/usuario/20170414104142667.png filename = DestDir+FileNAmenew; } Catch (Exception e) {Throw E; }}}Resumir
Lo anterior es el Webupploader que le presenté. La función de carga por lotes de imagen está equipada con código de ejemplo. Espero que te sea útil. Si tiene alguna pregunta, déjame un mensaje y el editor le responderá a tiempo. ¡Muchas gracias por su apoyo al sitio web de Wulin.com!