1. Ideas para cargar archivos de Struts
También he hablado sobre el componente FileUpload antes. Tiene funciones poderosas, pero la operación es complicada y complicada. Esta vez, las cargas de archivos también son compatibles con STRUT y FileUpload está empaquetado, lo cual es mucho más conveniente de usar.
Aquí viene una etiqueta y una clase:
<html: archivo propiedad = "correspondiente al nombre de la propiedad en ActionForm">
Use esta etiqueta para cargar archivos, pero para recibir el contenido, debe confiar en org.apache.struts.upload.formfile
La interfaz está completa.
2. Realización
SH.JSP:
<%@ page lenguaje = "java" import = "java.util.*" pageEncoding = "utf-8"%> <%@ taglib uri = "http://jakarta.apache.org/struts/tags-bean" prefix = "bean"%> <%@ taglib uri = "http://jakarta.apache.org/struts/tags-html" prefix = "html"%> <%@ taglib uri = "http://jakarta.apache.org/tags/tags-" prefix = "Logic"%> <! Doctype html público "-//dtml"-//dtml "-//dtml" HTML 4.01 Transitional // en "> <html> <head> <title> sh.jsp </title> <meta http-equiv =" content-type "content =" text/html; <html: archivo propiedad = "foto"> </html: file> <html: enviar value = "upload"> </html: enviar> </html: form> </body> </html>
Uploadform.java:
paquete com.zyy.struts.form; import org.apache.struts.action.actionform; import org.apache.struts.upload.formfile; public class uploadForm extiende ActionForm {private formfile Photo; Public Formfile getPhoto () {return Photo; } public void setPhoto (Formfile Photo) {this.photo = Photo; }} Iptimestamp.java:
paquete com.zyy.util; import java.text.simpledateFormat; import java.util.date; import java.util.random; clase pública iptimestamp {private simpledateFormat sdf = null; cadena privada ip = nulo; public Iptimestamp () {} public IpTimestamp (String IP) {this.ip = ip; } public String getIPTiMerand () {StringBuffer buf = new StringBuffer (); if (this.ip! = null) {string s [] = this.ip.split ("//."); para (int i = 0; i <s.length; i ++) {buf.append (this.addzero (s [i], 3)); }} buf.append (this.gettimestamp ()); Random r = new Random (); para (int i = 0; i <3; i ++) {buf.append (r.nextint (10)); } return buf.ToString (); } public String getDate () {this.sdf = new SimpleDateFormat ("yyyy-mm-dd hh: mm: ss.sss"); devolver esto.sdf.format (nuevo date ()); } public String getTimestamp () {this.sdf = new SimpleDateFormat ("yyyymmddhhmmsssss"); devolver esto.sdf.format (nuevo date ()); } private String addzero (string str, int len) {StringBuffer s = new StringBuffer (); S.Append (STR); while (s.length () <len) {s.insert (0, "0"); } return s.toString (); } public static void main (string args []) {System.out.println (new Iptimestamp ("192.168.1.1"). GetIptimerand ()); }}UploadAction.java:
paquete com.zyy.struts.action; import java.io.file; import java.io.fileOutputStream; import java.io.inputStream; import java.io.outputstream; import javax.servlet.http.httpservletReRest; import javax.servlet.http.httservletRespesse; importación; org.apache.struts.action.action; import org.apache.struts.action.actionform; import org.apache.structs.action.actionForward; importar org.apache.structs.action.actionmapping; import com.zyy.structs.form.uploadform; import com.zyy.util.iptimeStamp; public class Classporting extiende Action {Public ActionForwardForward Formulario, solicitud httpservletRequest, respuesta httpservletResponse) lanza la excepción {uploadForm uploadForm = (uploadform) form; IptimeStamp ips = new Iptimestamp (request.getRemoteaddr ()); // Nombre de archivo String FileName = ips.getIPtimerand () + "." + uploadform.getPhoto (). getFileName (). Split ("//.") [uploadForm.getPhoto (). getFileName (). Split ("//."). Longitud - 1]; // Archivo de ruta de salida Outfile = nuevo archivo (super.getServlet (). GetServletContext () .getRealPath ("/") + "cargar" + file.separator + filename); // La carpeta donde la imagen se almacena archivo de archivo = nuevo archivo (super.getServlet (). GetServletContext () .getRealPath ("/") + "cargar"); if (! file.exists ()) {file.mkdir (); } InputStream input = uploadform.getPhoto (). GetInputStream (); OutputStream output = new FileOutputStream (outFile); datos de byte [] = new Byte [1024]; int temp = 0; while ((temp = input.read (data, 0, 1024))! = -1) {output.write (data); } output.close (); input.close (); regresar nulo; }}struts-config.xml:
<? xml versión = "1.0" encoding = "iso-8859-1"?> <! DocType Struts-config public "-// Apache Software Foundation // Dtd Struts Configuration 1.2 // en" "http://jakarta.apache.org/dtds/dtds/dtruts-config_1_2.2.2.2.2. <Form-Beans> <Form-Bean name = "uploadform" type = "com.zyy.struts.form.uploadform"> </orm-bean> </orm-beans> <global-exceptions> </global-exceptions> <global-forwards> </global-forwards> <Action-mappings> <Action path = "/jsp/uping" atribute = "uploadform" tía "/"/"/"/"/"/"/"/"/jsp"/jsp "/jsp"/jsp " name = "uploadform" scope = "request" type = "com.zyy.struts.aaction.uploadaction"> </action> </action-mappings> <Message --resources parameter = "recurse.messageResources"/> </truts-config>
Dado que lo que estoy guardando es super.getServlet ().
Esta es la ruta real del directorio virtual en la carpeta de carga.
Se puede ver que el principio de carga de archivos en los puntales es el mismo que FileUpload, pero Struts está empaquetado, por lo que obviamente es mucho más conveniente de usar que usar el componente FileUpload solo.
Lo anterior es todo el contenido de este artículo. Espero que sea útil para el aprendizaje de todos y espero que todos apoyen más a Wulin.com.