1. Recursos de importação
2. Código JSP
<div> <belt> <pan>*</span> Nome do projeto: </elabel> <div> <input type = "text" value = "$ {proname}" stailholder = "" id = "" name = "proname" readOnly = "readOnly"> </div> </div <batel> <bel> <beli- "</"> </"> <baton> <baton> </diviSt = <baton> <div = <batel> <divy) <divy) <divyty = <belly) <siv = <baton> <div = <baton> DIVNONALTOLLY = </" <div> <div id = "filepicker"> selecione Picture </div> <button id = "btn-star"> Iniciar upload </butut> </div> </div> </div> <div> <belt> <div>*</span> Projeto Fatura upload: </bel> drag the photo here, you can select up to 300 photos in a single time</p> </div> </div> <div style="display:none;"> <div> <span>0%</span> <span></span> </div> <div> <div> <div> <div> id="filePicker2"></div> <div> <div> Start uploading</div> </div> </div> </div> </div> </div> </div> <div> <button onclick = "article_add ('', 'Invoicevo/save? & projectId = $ {projectId} & floicescan =', '10001');" type = "Button"> <i> </i> Salvar </botão> </div> </div> </div> 3. Código JS
<script type = "text/javascript"> var imagePath = null; function artigo_save () {alert ("A camada de bala será fechada automaticamente ao refrescar o pai."); window.parent.Location.Reload (); } /*Projeto fatura-add* / função artigo_add (title, url, w, h) {if (imagepath) {var index = layer.open ({type: 2, título: título, conteúdo: url+imagepath}); camada.full (índice); } else {alert ("Nenhum upload de imagem, faça o upload da imagem primeiro");}} $ (function () {$ ('. Skin-minimal input'). Icheck ({CheckClass: 'icheckbox-blue', Radioclass: 'iradio-blue', aumenteea: '20%'}); $ ("#btn-star"), state = "pendente", uploader; Receber o botão Opcional. 'GIF, JPG, JPEG, BMP, PNG', MIMETIPES: 'Image/*'}}); '</div>' + '<p> Aguarde o upload ... </p>' + '</div>'), $ img = $ li.find ('img'); src) {if (erro) {$ img.replacewith ('span> não pode visualizar </span>'); var $ li = $ ('#' + file.id), $ porcentagem = $ li .Find ('. $ li.find ("Estado"). Texto "Upload"); File.id) .Addclass ('Upload-STATE-SUCESSO') .Find (". error ");}); // Após a conclusão do upload, ele é bem-sucedido ou falhado, exclua a barra de progresso primeiro. UPLOWER.ON ('UPLOPLECOMPLETE', function (file) {$ ('#' + file.id) .find ('. Progress-box'). 'Upload'; $ btn.on ('clique', function () {if (state === 'upload') {uploader.stop ();} else {uploader.upload ();}}); (function ($) {// inicialização começa quando domégio {var $ wrap = $ ('. Informações. = 0, // otimize a retina, em retina, esse valor é 2 -RATIMENTO = Window.DevicePixelratio || 1, // Miniatura de tamanho miniário / RATIMATION / INFORMA DE INSULTIÇÃO DO INSULTIVO / PENTATESTE (INFORMA DE INFORMATESTA) Se o navegador suporta a imagem base64 isSupportBase64 = (function () {var data = new image (); var support = true; data.onload = data.onerror = function () {if (this.width! = 1 || this.Height! = 1) {suportes = false;}} data.src = "Dados: imagem/gif; base64, r0lgodlhaqabaiaaaaaaap /// ywaaaaaqabaaaCauwaow =="; Version.description; suporte de suporte = (function () {var s = document.createElement ('p'). estilo, r = 'transição' em s || 'webkittransition' em s || 'moztransition' em s || 'mstransition' em s || 'otransition' em s = null; retorno; (! Webuploader.uploader.support ('flash') && webuploader.browser.ie) {// flash está instalado, mas a versão é muito baixa. quebrar o caso 'download.Fail:' Instalação ') '"'; if (webuploader.browser.ie) {html + = 'classId =" clsid: d27cdb6e-ae6d-11cf-96b8-4445553540000 "';} html + = 'width =" 100%"estily =" despojo: 0 "0">; /> ' +' <param name = "wmode" value = "transparent" /> ' +' <param name = "wmode" value = "transparent" /> ' +' <param name = "wmode" value = "transparent" /> '' ' +' name = "wmode" = "transparent" /> '' '<param <param name = "Permirpact" Value = "sempre"/> + '</fated>'; src = "http://www.adobe.com/macromedia/style_guide/images/160x41_get_flash_player.jpg"/> </a> '); return; chunked : false, chunkSize : 512 * 1024, server : 'invoiceVo/news_uploder?&projectId=${projectId}', // runtimeOrder: 'flash', // accept: { // title: 'Images', // extensions: 'gif,jpg,jpeg,bmp,png', // mimeTypes: 'image/*' // }, // Desativar a função de arrasto global. uploader.on ('dndaccept', function (itens) {var negado = false, len = items.length, i = 0, // modifique JS tipo unallowed = 'text/plany; application/javascript'; para (; i <len; i ++) {// se na lista (~ ~ uNallowEd.iSexof (itan; i]; ! negado; //}); {var $ li = $ ('<li id = "' + file.id + '' '' ' +' <p> ' + file.name +' </p> ' +' <p> </p> ' +' <p> <p> </span> </p> ' +' </li>), $ btns = $ ('<div>' ' + span) </span) </p>' + ' +' </li>), $ btns = $ ('<div>' ' + relet + span) </spannet </plan) </p>' + '</li>), $ btns = $ (' <div> '' + relet </span) </p> ' +' + '</li>), $ btns = $ ('> '' ' + span) + '<span> gire para a esquerda </span> </div>') .appendTo ($ li), $ prgress = $ li .find ('p.Progress span'), $ wrap = $ li .find ('p.imgwrap'), $ info = $ ('<p> </p>'), chuveiro = function (code) {switch (code) (code (code) (code), (code), (code), (code), (code), (code), (code), (code). Break; uploader .makethumb (arquivo, function (erro, src) {var iMg; if (error) {$ wrap.text ('não é possível visualizar'); return;} if (iSsupportBase64) {img = $ ('<img src = "'+src+'">'); $ wrap.ement (). 'Lib/webUploader/0.1.5/Server/Visuew.php', {Method: 'Post', Data: SRC, Datatype: 'JSON'}) .DONE (function (Response) {if (Responst.Result) {img = $ ('<img src = "' '+Response.Result+"> "); {$ wrap .Text (Erro de visualização "); if (prev === 'fila') {$ li.off ('mouseenter mouseleave'); 'interrupção') {console.log (file.statustext); $ info.remove (); $ BTNS.STOP (). upload.removefile (arquivo); Deg, 'Transforme': deg}); Removerfile (arquivo) {var $ li = $ ('#' + file.id); US $ updatestatus (); {text = 'Uploaded' + stats.successnum + 'foto para xx álbum,' + stats.uploadfailnum + 'upload de foto falhou, <a href = "#" rel = "nofollow externo" r = "nofollow"> re-upload </a> falha na imagem ou <a href = "#" }} else {stats = uploader.getStats (); } $ info.html (text); $ queue.hide (); statusBar.Removes Case 'Confirme': $ Progresso.hide (); O upload.getStats (); $ porcentagem = li .Find ('Progresso'); $ placehold.addclass (elemento invisível '); Removerfile (arquivo); (Response.status == "Erro") Alerta (Response.error); SetState ('PAUSE'); O upload} elimine (State === ' '.Ignore', function () {alerta ('TODO'); }) (jQuery); </script> Perceber:
4. Código do controlador
/** * Pule para a página em que a fatura é carregada * @param pronome * @param mapa * @return */@requestMapping (value = "/upload") public String FloiceUpload (String proname, Long Id, map <string, object> map) {map.put ("proname", proname); Projectservice.getProject (ID); map.put ("projectId", id); retornar "Project/Floiceupload"; }/** * Carregue a fatura e salve o banco de dados * arquivo @param * @param request * @param Resposta * @return */@ResponseBody @RequestMapping (value = "/news_uploder", método = {requestmethod.post, requestmethod.get}, productes = "Application/json; charset; Arquivo multipartFile [], ProjectId Long, solicitação httpServletRequest, httpServletResponse resposta) {string sinalizador = null; JsonObject jsonObject = new jsonObject (); tente {webUploaderutil webUPLOADERUTIL = new WebPloaderutil (); webupLoaderutil.upload (arquivo [0], "Upload/floice/", solicitação); flag = webUploaderutil.getFilename (); jsonObject.put ("filepath", sinalizador); jsonObject.put ("status", "sucesso"); } catch (Exceção e) {e.printStackTrace (); } retornar jsonObject; } 5. Tool class package com.softjx.util;/** *Project Name: QDLIMAP *File Name: WebuploaderUtil.java *Package Name: com.ltmap.platform.cms.util *Date: April 13, 2017 at 6:30:45 pm *Copyright (c) 2017,[email protected] All Rights Reserved. */ importar java.io.file; importar java.text.simpledateFormat; importar java.util.date; importar javax.servlet.http.httpServletRequest; importar org.springframework.web.multipart.multipartFile; /** *Título: webUploaderutil <br/> *Descrição: *@Empresa: litu hi-tech <br/> *@autor: liu yunsheng *@versão: v1.0 *@Desde: jdk 1.8.0_40 *@Data: 13 de abril, 2017 às 6:30:45 pm <br/> */public ClassLOM "JPG, PNG, GIF, JPEG"; // Permitir formato de arquivo Private Long Permize = 2L; // Permitir tamanho de arquivo Private String FileName; string privada [] nomes de arquivos; public string getallowsuffix () {return permitirfix; } public void se setAllowsuffix (String permitefix) {this.allowsuffix = permiteffix; } public long getallowsize () {return permite*1024*1024; } public void setAllowsize (Long Permize) {this.allowsize = Permize; } 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 às 10:17:35 * @throws * / private string getFilenameNew () {simledate SimpledateFormat ("yyyymmddhhmmsssss"); retornar fmt.format (new Date ()); } / ** * * @title: uploads * @Description: TODO * @Param: @Param Arquivos * @param: @param destdir * @param: @param request * @param: @throws excepção * @return: void * @author: liU yunsheng * @date: abril * 2017 às 10:177:17:17:110 * @author: liU yunsheng * @date: abril * (2017 a 10:17: 10:17: @author: liU yunsheng * Arquivos, String Destdir, HttpServletRequest Request) lança exceção {String path = request.getContextPath (); String basalepath = request.getScheme ()+": //"+request.getServerName ()+":"+request.getServerport ()+path; tente {fileNames = new String [files.length]; int index = 0; para (arquivo multipart -arquivo: arquivos) {string suffix = FILE.GETORGINALFILENAME (). substring (FILE.GETORGINALFILENAME (). LastIndexOf (".")+1); int length = getallowsuffix (). indexOf (sufixo); if (comprimento == -1) {lança nova exceção ("Faça o upload do arquivo no formato permitido"); } if (file.getSize ()> getallowsize ()) {lança nova exceção ("o tamanho do arquivo que você carregou está fora de intervalo"); } String realpath = request.getSession (). GetServletContext (). GetRealPath ("/"); Arquivo Destfile = novo arquivo (RealPath+Destdir); if (! Destfile.Exists ()) {Destfile.mkdir (); } String filenameNew = getFileNameNew ()+"."+Sufix; // arquivo f = novo arquivo (Destfile.getabsolutefile ()+"//"+filenamenew); file.transferto (f); F.CreateNewFile (); Nomes de arquivo [index ++] = BasEpath+Destdir+FileNameNew; }} catch (Exceção e) {tiro e; }} / ** * * @title: upload * @Description: TODO * @param: @param arquivo * @param: @param Destdir * @param: @param request * @param: @throws excepção * @return: void * @author: liU yunsheng * @Date: abril * 2017 at 10:110: 10:Turn: Void * @author: liU yunsheng * String Destdir, httpServletRequest Request) lança Exceção {String path = requestContextPath (); // http: // localhost: 8088/huahang string basalepath = request.getscheme ()+": //"+request.getServername ()+":"+request.getServerport ()+path; tente {string suffix = file.getoriginalfilename (). substring (file.getoriginalfilename (). lastIndexOf (".")+1); int length = getallowsuffix (). indexOf (sufixo); if (comprimento == -1) {lança nova exceção ("Faça o upload de arquivos no formato permitido"); } if (file.getSize ()> getallowsize ()) {lança nova exceção ("o tamanho do arquivo que você carregou excedeu o intervalo"); } String realpath = request.getSession (). GetServletContext (). GetRealPath ("/")+"/"; Arquivo Destfile = novo arquivo (RealPath+Destdir); if (! Destfile.Exists ()) {Destfile.mkdirs (); } String filenameNew = getFileNameNew ()+"."+Sufixo; Arquivo f = novo arquivo (destfile.getabsolutefile ()+"/"+filenamenew); file.transferto (f); F.CreateNewFile (); // Inclua o caminho completo do site http: // localhost: 8080/qdlimap/upload/user/20170414104142667.png // filename = basepath+destdir+filenenew; // retorna o upload/user/user/201704141414142667.png nome de arquivo = destdir+filenamenew; } catch (Exceção e) {tiro e; }}}Resumir
O exposto acima é o WebUploader que eu apresentei a você. A função de upload em lote de imagem está equipada com código de exemplo. Espero que seja útil para você. Se você tiver alguma dúvida, deixe -me uma mensagem e o editor responderá a você a tempo. Muito obrigado pelo seu apoio ao site wulin.com!