В нашей веб -разработке много раз нам нужно загрузить некоторые файлы с машины на веб -сервер.
Например: система BBS, когда пользователи используют эту систему, они могут загружать некоторые изображения и документы машины на сервер. Тогда другие пользователи могут скачать эти файлы. Таким образом, мы можем запрограммировать загрузку файла сами, но лучший способ - использовать некоторые существующие компоненты, чтобы помочь нам реализовать эту функцию загрузки.
Общие компоненты загрузки :
Commons FileUpload от Apache
Javazoom - это загрузка
jspsmartupload
Адрес загрузки FileUpload:
http://commons.apache.org/fileupload/
Скачать: commons-fileupload-1.2.2-bin.zip get: commons-fileupload-1.2.2.jar
http://commons.apache.org/io/
Скачать: Commons-IO-1.4-bin.zip get: Commons-IO-1.4.jar
upload.jsp
код;
<%@ page language = "java" contentType = "text/html; charset = utf-8"%> <html> <head> <title> с использованием загрузки Commons для загрузки файла </title> </head> <style>* {font-family: "安体"; font-size: 14px }</style><body><p align="center"> Please select the file you want to upload</p><form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data"> <table align="center"> <tr> <td>Uploader: </td> <td> <input name = "name" type = "text" id = "name" size = "20"> </td> </tr> <tr> <td> Файл загрузки: </td> <td> <input name = "file" type = "size =" 20 "> </td> </tr> <tr> <td> </td> <td> <inputul type = "reset" name = "reset" value = "reset"> </td> </tr> </table> </form> </body> </html>Fileuploadservlet.java код:
пакет com.b510.example; импорт java.io.file; импорт java.io.ioexception; импорт java.util.*; import javax.servlet.servletconfig; импорт javax.servlet.servletcontext; import.servlet.servlet.servletexcept javax.servlet.http.httpservlectrequest; import javax.servlet.http.httpservletresponse; импорт org.apache.commons.fileupload.fileitem; импорт org.apache.commons.fileupload.fileuadexception; org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;/** * * @author XHW * * @date 2011-7-26 * */public class FileUploadServlet extends HttpServlet { private static final long serialVersionUID = -7744625344830285257L; Private ServletContext SC; Private String SavePath; public void Doget (httpservletrequest, httpservletresponse response) бросает Servletexception, ioException {DoPost (запрос, ответ); } public void init (конфигурация SERVLETCONFIG) {// Параметр инициализации, установленную в web.xml savepath = config.getinitparameter ("savePath"); sc = config.getServletContext (); } public void Dopost (httpservletrequest, httpservletresponse response) throws servletexception, ioexception {request.setcharacterencoding ("utf-8"); DiskFileItemfactory Factory = new DiskFileItemFactory (); ServletFileUpload upload = new ServletFileUpload (Factory); try {list elects = upload.parserequest (request); Итератор itr = item.iterator (); while (itr.hasnext ()) {fileitem item = (fileitem) itr.next (); if (item.isformfield ()) {System.out.println ("Имя параметра формы:" + item.getfieldname () + ", значение параметра формы:" + item.getString ("utf-8")); } else {if (item.getName ()! = null &&! item.getName (). equals (""))) {System.out.println ("Размер файла загрузки:" + item.getSize ()); System.out.println ("upload file type:" + item.getContentType ()); // item.getName () возвращает полное имя пути загруженного файла в клиентской системе. File tempfile = new File (item.getName ()); // загрузка файла файла сохранения файл файла = new File (sc.getRealPath ("/") + savePath, tempfile.getName ()); item.write (file); request.setattribute ("upload.message", "Загрузка файла была успешной!"); } else {request.setAttribute ("upload.message", "Нет файла загрузки выбран!"); }}}}} catch (fileuploadexception e) {e.printstacktrace (); } catch (Exception e) {e.printstackTrace (); request.setattribute ("upload.message", "opload file не удастся!"); } request.getRequestDispatcher ("/uploadresult.jsp"). }}uploadresult.jsp код:
<%@ page language = "java" import = "java.util.*" pageencoding = "utf-8"%> <! Doctype html public "-// w3c // dtd html 4.01 Transitional // en"> <html> <Head> uploadResult </title> <meta http-queciv = "haute> uploadResult </title> <Meta http-ockiv =" content = "no-cache"> <meta http-equiv = "cache-control" content = "no-cache"> <meta http-equiv = "expires" content = "0"> <meta http-equiv = "Keywords" Content = "Ключевое слово1, ключевое слово2, ключевое слово3"> <meta http-equivive = "description1 hite his his hite his his hit eavize =" rel = "styleSheet" type = "text/css" href = "styles.css"> -> </head> <body> $ {requestScope ['upload.message']} <a href = "/upload/oploadfile.jsp"> upload file </a> </body> </html>web.xml
Код:
<? xml version = "1.0" Encoding = "utf-8"?> <web-app arser = "2,5" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http://www.w3.org/2001/xmlschema electan "/www.w3. xsi: schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5 Компонент </description> <shiple-name> Это отображающее имя моего J2EE Component </display-name> <servlet-name> fileUploadServlet </servlet-name> <serlet-class> com.b510.example.fileuploadservlet </servlet-class> <! --Set initialization parameters --> <init-param> <param-name>savePath</param-name> <param-value>uploads</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>FileUploadServlet</servlet-name> <url-pattern>/servlet/fileServlet</url-pattern> </servlet-mapping> <Welcome-file-list> <selcoveryfile> index.jsp </wervedied-file> <belcelporting> uploadfile.jsp </wervedied-file> </werveding-file-list> </web-app>
Выше всего содержание этой статьи. Я надеюсь, что это будет полезно для каждого обучения, и я надеюсь, что все будут поддерживать Wulin.com больше.