1. Идеи для загрузки файлов стойки
Я также говорил о компоненте FileUpload раньше. Он имеет мощные функции, но операция сложна и сложна. На этот раз загрузки файлов также поддерживаются в Strust, и FileUpload упакована, что гораздо удобнее использовать.
Вот тег и класс:
<html: file Property = "Соответствует имени свойства в ActionForm">
Используйте этот тег для загрузки файлов, но для получения содержимого вы должны полагаться на org.apache.struts.upload.formfile
Интерфейс завершен.
2. Реализация
sh.jsp:
<%@ page language = "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/struts/tags-logic" prefix = "logic"%> <! doctype html html html html html html html html html Html 4.01 Transitional // en "> <html> <head> <title> sh.jsp </title> <meta http-equiv =" content-type "content =" text/html; ectype = "multipart/form-data"> <html: file property = "photo"> </html: file> <html: отправить значение = "upload"> </html: отправить> </html: form> </body> </html>
Uploadform.java:
пакет com.zyy.struts.form; import org.apache.struts.action.actionform; import org.apache.struts.upload.formfile; открытый класс uploadform extends actionform {private formfile photo; public formfile getPhoto () {вернуть фото; } public void setPhoto (formfile photo) {this.photo = photo; }} Iptimestamp.java:
пакет com.zyy.util; import java.text.simpledateformat; import java.util.date; импорт java.util.random; public class iptimestamp {private simpledateformat sdf = null; Приватная строка ip = null; 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 ("//"); for (int i = 0; i <s.length; i ++) {buf.append (this.addzero (s [i], 3)); }} buf.append (this.getTimeStamp ()); Случайный r = new Random (); for (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"); вернуть this.sdf.format (new Date ()); } public String getTimestAmp () {this.sdf = new SimpleDateFormat ("yyyyMmddhhmmsssssss"); вернуть this.sdf.format (new 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:
пакет com.zyy.struts.action; импорт java.io.file; импорт java.io.fileOutputStream; импорт java.io.inputStream; импорт java.io.outputStream; import javax.servlet.http.httpservlectrequest; import javax.servlet.http.htplsevonse; org.apache.struts.action.action; import org.apache.strut.action.actionform; import org.apache.structs.action.actionForward; import org.apache.structs.action.actionMaping; импорт com.zyy.structs.form.uploadform; импорт com.zylame.iptimempampmapmessmappormempation. Form, httpservletrequest запрос, httpservletresponse response) throws exection {uploadform uploadform = (uploadform) form; Iptimestamp ips = new iptimestamp (request.getRemoteaddr ()); // Имя файла string fileName = ips.getiptimerand () + "." + uploadform.getPhoto (). getFilEname (). Split ("//") [uploadform.getPhoto (). getFilename (). Split ("//"). Длина - 1]; // Файл выходного пути outfile = new File (super.getServlet (). GetServletContext () .getRealPath ("/") + "upload" + file.separator + fileName); // папка, где изображение хранится файл файла = новый файл (super.getServlet (). GetServletContext () .getRealPath ("/") + "upload"); if (! file.exists ()) {file.mkdir (); } InputStream input = uploadform.getPhoto (). GetInputStream (); OutputStream output = new FileOutputStream (Outfile); байтовые данные [] = новый байт [1024]; int temp = 0; while ((temp = input.read (data, 0, 1024))! = -1) {output.write (data); } output.close (); input.close (); вернуть ноль; }}struts-config.xml:
<? xml version = "1.0" Encoding = "iso-8859-1"?> <! Doctype struts-config public "-// Apache Software Foundation // DTD Configuration 1.2 // en" <bome-beans> <form-bean name = "uploadform" type = "com.zyy.struts.form.uploadform"> </form-bean> </form-beans> <blodal-exceptions> </global-exceptions> <blobal-forwards> </global-forwards> <caption-mappings> <Действие = "/jsp/opload" attrubuit = "adpload> into" into "hop.sp. name = "uploadform" scope = "request" type = "com.zyy.struts.action.uploadaction"> </action> </action-mappings> <Сообщение-resources parameter = "resource.messageresources"/> </struts-config>
Поскольку то, в чем я сохраняю, Super.getServlet (). GetServletContext (). GetRealPath ("/")+ "upload"
Это реальный путь виртуального каталога под папкой загрузки.
Можно видеть, что принцип загрузки файлов в стойках такой же, как и FileUpload, но стойки упакованы, поэтому он, очевидно, гораздо более удобен в использовании, чем использование только компонента FileUpload.
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.