В целом, есть два способа загрузки изображений. Файлы изображений, записанные в базу данных, должны быть преобразованы в формат двоичного потока, который занимает пространство базы данных и подходит для хранения небольшого количества изображений. что они относительно безопасны и их нелегко избежать пользователей.
Реализовано в Struts2 (в качестве примера с примером загрузки изображения)
1. Список кода fileupload.jsp выглядит следующим образом:
<%@ page language = "java" import = "java.util.*" pageencoding = "utf-8"%> <%@ taglib prefix = "s" uri = "/struts-tags"%> <html> < Head> <Title> FileUplaodDemo в struts2 </title> </head> <body> <s: form action = "fileupload" method = "post" enctype = "multipry/form-data" Space = "/"> <s: имя файла = "myfile" label = "myfile"> </s: файл> <s: textfield name = "caption" label = "caption"> </s: textfield> <s: отправить label = "Отправить ">/s: отправить> </s: форма> </body> </html>
2. Список функций Showupload.jsp заключается в следующем:
<%@ page language = "java" import = "java.util.*" pageencoding = "utf-8"%> <%@ taglib prefix = "s" uri = "/struts-tags"%> <html> < Head> <Title> ShowUpload </title> </head> <body> <div style = "padding: 3px; граница: сплошной 1px #ccccc; text-align: center"> <img src = "uploadima ges/<s : value Property = "ImageFilEname"/> "/> <br/> <s: значение свойства =" caption "/> </div>/body> </html>
3. Кодовый список FileUploadAction.java выглядит следующим образом:
пакет com.chris; импорт java.io.*; import java.util.date; import org.apache.struts2.servletactionContext; импорт com.opensymphony.xwork2 572146812454L; Private Static Final Buffer_size = 16 * 1024; // Обратите внимание, что при загрузке файла <S: File // связан с MyFile, MyFileContentType, MyFileFilename./so, myfileContenttyp Метод SET LENAME Time Private MyFile; SetMyFileContentType (String ContentType) {System.out .println ("Тип файла:" + contentType); ; this .filename = filename;} public void setMyfile (file myfile) {this .myfile = myfile;} public String getImagefilEname () {ret ImageFilEname;} public String getCaption () {ret urn caption;} public void setCaption (строковое сборы. ) {this .caption = caption;} private static void copy (файл src, файл dst) {try {inputStream in = null; outputStream out = null; try {in = new BufferedInptream (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);}} наконец {if (if (if (if (if (if (if (if (if (if (if (if (if ( null! = in) {in.close ();} if (null! = out) {out.close ();}}} catch (exception e) {e.printstacktrace ();}} частная статическая строка getextention (строка filename) {int pos = filename.lastindexof ("."); return filename.substring (pos);}@overdepublic string () {imagefilename = new Date (). getTime () + getExtention (filename); Новый файл (ServletActionContext.getServletContext (). getRealPath ("uploadImage") + "/" + imageFilename); Copy (myfile, imagefile); return успех;}}ПРИМЕЧАНИЕ. В настоящее время, только для удобства реализации действий, actionSopport наследуется, и метод exepute () execute ()
Любой Pojo в Struts2 может быть использован в качестве действия
4.Struts.xml Список выглядит следующим образом:
<? xml version = "1.0" Encoding = "UTF-8"?> <! Doctype struts public "-// Apache Software Foundation // DTD Struts Configuration 2.0 // en" "http: // strut s.apache.org /dtds/struts-2.0.dtd "> <struts> <package name =" Пример "space ="/"extends =" struts-default "> <name =" fileupload "> <receptor -ref name =" fileuploadstack " /> <sesult> /showupload.jsp </result> </action> </package> </struts>
5. Список web.xml выглядит следующим образом:
<? xml version = "1.0" Encoding = "utf-8"?> <web-app ression = "2.4" xmlns = "http://java.sun.com/xml/ns/j2ee" xmlns: xsi = " http://www.w3.org/2001/xmlschema-instance"xsi:schemalocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns//j2ee http://java.sun.com/xml/ns//j2ee j2ee/web-app_2_4.xsd "> <filter> <filter-name> struts-cleanup </filter-name> <filter-class> org.apache.struts2.dispatcher.actionContextCleanup </filter-class> </filter> <Filter-Mapping> <Filter-name> struts-cleanup </filter-name> <url-pattern>/* </url-pattern> </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-pattern >/ *</url-pattern> </filter-mapping> <selcopply-file-list> <selcload-file> index.jsp </wervedied-file> </werveding-file-list> </web-app>
Приведенный выше контент - это все содержание того, как загружать изображения в Java Struts2, представленные вам.