Em geral, existem duas maneiras de fazer upload de imagens. Os arquivos de imagem gravados no banco de dados precisam ser convertidos em um formato de fluxo binário, que ocupa o espaço do banco de dados e é adequado para o armazenamento de um pequeno número de imagens. que eles são relativamente seguros e não são facilmente evitados pelos usuários.
Implementado no STRUTS2 (Tomando o upload da imagem como exemplo)
1.A lista de código FileUpload.jsp é a seguinte:
<%@ Page Language = "java" import = "java.util. Chefe> <Title> O FILEUPLAODDEMO em STRUTS2 </title> </ad Head> <body> <s: formaction = "fileUpload" method = "post" Enctype = "Multipart/Form-Data" Space = "/"> <S: Nome do arquivo = "MyFile" Label = "MyFile"> </s: File> <S: TextField Name = "Legend" Label = "Legenda"> </s: Textfield> <S: Submit Label = "Enviar" ">/s: envie> </s: form> </body> </html>
2. A lista de funções do showupload.jsp é a seguinte:
<%@ Page Language = "java" import = "java.util. Chefe> <Title> exibirpload </ititle> </ad Head> <body> <div style = "preenchimento: 3px; borda: sólido 1px #ccccccc; text-align: center"> <img src = "uploadima ges/<s : Property Value = "ImageFilename"/> "/> <r/> <S: Property Value =" Legend "/> </div>/body> </html>
3. A lista de código do FileUploadaction.java é a seguinte:
pacote com.chris; importar java.io. 572146812454l; private estático final int buffer_size = 16 * 1024; // Observe que quando o arquivo é carregado, <s: file // está ligado ao myFile, myFileContentType, myFileFilename./so, MyFilecOntEntType, MyFileFi deve ser fornecido a ser fornecido a ser fornecido. Time Lename Method's Método Private MyFile; setMyFilEContentType (String contentType) {System.out .Println ("Tipo de arquivo:" + ContentType); ; this .filename = filename;} public void setMyfile (arquivo myfile) {this .myfile = myfile;} public string getImageFilename () {ret imagefilename;} public string getCaption () {ret urn legend;} vazio público se setCaption (string getCaption () {retirn legend;} vazio público definido ) {this .Caption = Legenda;} cópia estática privada (arquivo src, arquivo dst) {try {inputStream in = null; outputStream out = null; try {in = new bufferedInputStream (new FileInputStream (src), bu ffer_size); out = new BufferedOutputStream (new FileOutputStream (dst), buffer_size); byte [] buffer = new Byte [buffer_size]; while (in.read (buffer)> 0) {out.write (buffer);}} finalmente {if (se (se null! = in) {in.close ();} if (null! = out) {out.close ();}}} catch (Exceção e) {E.printStacktrace ();}}}} string estática privada getExtion (string (string nome do arquivo) {int pos = filename.lastIndexOf ("."); retorna o arquivo do arquivo.substring (pos);}@substituir String de string executado () {imagefilename = new Date (). gettime () + getextent (arquivo); novo arquivo (servletActionContext.GetServletContext ().Nota: No momento, apenas para a conveniência de implementar a ação, o ACTIONSupport é herdado e o método de Execute () substituto é
Qualquer pojo em struts2 pode ser usado como uma ação
4.Struts.xml Lista é a seguinte:
<? xml versão = "1.0" coding = "utf-8"?> <! Doctype Struts public "-// Apache Software Foundation // DTD Struts Configuration 2.0 // EN" "http: // strut s.apache.org /dtds/struts-2.0.dtd "> <truts> <package name =" exemplo "namespace ="/"estends =" struts-default "> <ação name =" fileUpload "> <interceptor -ref name =" fileUploadstack " /> <SILLD> /showupload.jsp </resultado> </action> </cackage> </stuts>
5. A lista Web.xml é a seguinte:
<? xml versão = "1.0" coding = "utf-8"?> <web-app versão = "2.4" xmlns = "http://java.sun.com/xml/ns/j2ee" xmlns: xsi = " http://www.w3.org/2001/xmlschema-instance"xsi:schemalocation=iss J2EE/Web-App_2_4.xsd "> <filter> <filter-name> struts-clim-cleanup </filter-name> <filter-class> org.apache.struts2.dispatcher.actionContextCleanup </filter-class> </filter> <Filter-Mapping> <filtro-name> struts-cleanup </filter-name> <url-tattern>/* </url-tattern> </filter-mapping> <filter> <filter-name> struts2 </fi lter -name> <filter-Class> org.apache.struts2.dispatcher.filterdispatcher </filter-class> </filter> <filter-mapping> <filter-name> struts2 </filter-nA me> <url-tattern >/ *</url-tattern> </filter-mapping> <lorde-file-list> <lmed-fil-bile> index.jsp </weld-fil-bile> </-Welcome-File-List> </web-app>
O conteúdo acima é todo o conteúdo de como fazer upload de imagens no Java Struts2 apresentado a você.