Use the struts2 framework to upload and download files

Source: Internet
Author: User

In the struts2 framework, follow the conventions to be greater than the configuration. The following is a small example of uploading and downloading files.

1. File database (MySQL is used)

There is only one t_file table.

ID: int primary key

Name: varchar

Size: Float

Contenttype: varchar


2. Upload. jsp

<% @ Page Language = "Java" Import = "Java. util. * "pageencoding =" UTF-8 "%> <% @ taglib prefix =" C "uri =" http://java.sun.com/jsp/jstl/core "%> <! Doctype HTML> <HTML lang = "En-us"> 


3. DB. Properties

driver=com.mysql.jdbc.Driverurl=jdbc\:mysql\:///filename=rootpwd=root

4. Struts. Properties

Struts. multipart. savedir: the location where the file is cached on the disk.

Struts. multipart. maxsize: maximum value of the uploaded file. Unit: B

struts.action.extension=actionstruts.multipart.saveDir=C:/tempstruts.multipart.maxSize=20971520

5. struts2.xml

<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE struts PUBLIC"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN""http://struts.apache.org/dtds/struts-2.3.dtd"><struts><package name="mypackage" extends="struts-default" ><action name="file" class="com.kaishengit.action.FileAction"><result>/WEB-INF/views/upload.jsp</result></action><action name="upload" class="com.kaishengit.action.FileAction" method="upload"><result type="redirectAction"><param name="actionName">file</param></result></action><action name="download" class="com.kaishengit.action.FileAction" method="download"><result name="success" type="stream">  <param name="contentType">${contentType}</param>  <param name="contentLength">${fileSize}</param>  <param name="inputName">mystream</param>  <param name="contentDisposition">attachment;filename="${fileName}"</param>  <param name="bufferSize">1024</param></result></action></package></struts>

6. fileaction. Java

Package COM. kaishengit. action; import Java. io. bufferedinputstream; import Java. io. bufferedoutputstream; import Java. io. file; import Java. io. fileinputstream; import Java. io. filenotfoundexception; import Java. io. fileoutputstream; import Java. io. inputstream; import Java. util. list; import COM. kaishengit. entity. document; import COM. kaishengit. service. documentservice; import COM. opensymphony. xwork2.action; Public Cl Ass fileaction implements action {// convention is greater than the configuration of private string DESC; private file Doc; private string docfilename; // file name, according to the file name in the form is Doc, after adding filename to the doc is the actual name of the uploaded file. The conventions are greater than private string doccontenttype. // same as private list <document> list; private string ID; private string contenttype; private long filesize; private string filename; documentservice DS = new documentservice (); Public String execute () throws exc Eption {list = Ds. findall (); Return success;} Public String upload () throws exception {system. out. println (DESC); // obtain the input file name bufferedinputstream Bis = new bufferedinputstream (New fileinputstream (DOC )); bufferedoutputstream Bos = new bufferedoutputstream (New fileoutputstream (new file ("C:/upload", docfilename); byte [] buffer = new byte [512]; int Len =-1; while (LEN = bis. read (buffer ))! =-1) {Bos. write (buffer, 0, Len);} // do not forget flush and closebos. flush (); Bos. close (); bis. close (); DS. save (docfilename, Doc. length (), doccontenttype); Return success;} Public String download () {return success;} public inputstream getmystream () throws filenotfoundexception {document D = Ds. findbyid (ID); file = new file ("C:/upload", D. getname (); filesize = D. getsize (); contenttype = D. getcontenttype (); filename = D. getname (); return New fileinputstream (File) ;}// get setpublic list <document> getlist () {return list;} Public String GETID () {return ID ;} public void setid (string ID) {This. id = ID;} Public String getdesc () {return DESC;} public void setdesc (string DESC) {This. desc = DESC;} public void setlist (list <document> List) {This. list = List;} public file getdoc () {return Doc;} public void setdoc (File Doc) Export this.doc = Doc;} Public String getdocfilename () {return docfilename ;} public void setdocfilename (string docfilename) implements filename = docfilename;} Public String getdoccontenttype () {return doccontenttype;} public void setdoccontenttype (string doccontenttype) implements contenttype = doccontenttype ;} public String getcontenttype () {return contenttype;} public void setcontenttype (string contenttype) {This. contenttype = contenttype;} public long getfilesize () {return filesize;} public void setfilesize (long filesize) {This. filesize = filesize;} Public String getfilename () {return filename;} public void setfilename (string filename) {This. filename = filename ;}}


7. Document. Java

package com.kaishengit.entity;public class Document {private int id;private String name;private long size;private String contentType;public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public long getSize() {return size;}public void setSize(long size) {this.size = size;}public String getContentType() {return contentType;}public void setContentType(String contentType) {this.contentType = contentType;}}


8. documentservice. Java

package com.kaishengit.service;import java.util.List;import com.kaishengit.dao.DocumentDao;import com.kaishengit.entity.Document;public class DocumentService {DocumentDao dao = new DocumentDao();public List<Document> findAll() {return dao.findAll();}public void save(String docFileName, long length, String docContentType) {Document d = new Document();d.setContentType(docContentType);d.setName(docFileName);d.setSize(length);dao.save(d);}public Document findById(String id) {return dao.findById(id);}}

9. documentdao. Java

package com.kaishengit.dao;import java.sql.ResultSet;import java.sql.SQLException;import java.util.List;import com.kaishengit.entity.Document;import com.kaishengit.util.DBHelp;import com.kaishengit.util.RowMapper;public class DocumentDao {DBHelp<Document> db = new DBHelp<Document>();public List<Document> findAll() {final String sql = "SELECT id,`name`,size,contentType FROM t_file";return db.executeQueryForList(sql, new DocumentRowMapper());}private class DocumentRowMapper implements RowMapper<Document>{public Document mapRow(ResultSet rs) throws SQLException {Document d = new Document();d.setContentType(rs.getString("contentType"));d.setId(rs.getInt("id"));d.setName(rs.getString("name"));d.setSize(rs.getLong("size"));return d;}}public void save(Document d) {final String sql = "INSERT INTO t_file(`name`,size,contentType) VALUES(?,?,?)";db.executeSQL(sql, d.getName(),d.getSize(),d.getContentType());}public Document findById(String id) {final String sql = "SELECT id,`name`,size,contentType FROM t_file where id=?";return db.executeQueryForObject(sql, new DocumentRowMapper(), id);}}

10. dbhelp. Java

Package COM. kaishengit. util; import Java. io. ioexception; import Java. io. inputstream; import Java. SQL. connection; import Java. SQL. preparedstatement; import Java. SQL. resultset; import Java. SQL. sqlexception; import Java. SQL. statement; import Java. util. arraylist; import Java. util. list; import Java. util. properties; import Org. apache. commons. DBCP. basicdatasource;/*** database access tool class **/public class dbhelp <t> {private s Tatic basicdatasource Ds; static {inputstream stream = dbhelp. class. getclassloader (). getresourceasstream ("DB. properties "); properties P = new properties (); try {P. load (Stream); DS = new basicdatasource (); DS. seturl (P. getproperty ("url"); DS. setpassword (P. getproperty ("PWD"); DS. setdriverclassname (P. getproperty ("driver"); DS. setusername (P. getproperty ("name"); DS. setinitialsize (5); DS. setmaxactive (20); DS. set Maxwait (5000); DS. setminidle (8); system. out. println ("data source created ........................... ");} catch (ioexception e) {e. printstacktrace () ;}}/*** get database connection object * @ return connection Class Object */public connection getconnection () {connection conn = NULL; try {conn = Ds. getconnection ();} catch (sqlexception e) {e. printstacktrace () ;}return conn;} public list <t> executequeryforlist (string SQL, rowmapper <t> RM, object... ARG S) {connection conn = NULL; preparedstatement stat = NULL; resultset rs = NULL; List <t> List = new arraylist <t> (); try {conn = getconnection (); stat = Conn. preparestatement (SQL); For (INT I = 0; I <args. length; I ++) {stat. setobject (I + 1, argS [I]);} rs = stat.exe cutequery (); While (RS. next () {t obj = RM. maprow (RS); list. add (OBJ) ;}} catch (exception e) {e. printstacktrace ();} finally {close (RS, stat, Conn);} r Eturn list;} public object executequeryforfunction (string SQL, object... ARGs) {connection conn = NULL; preparedstatement stat = NULL; resultset rs = NULL; object result = NULL; try {conn = getconnection (); stat = Conn. preparestatement (SQL); For (INT I = 0; I <args. length; I ++) {stat. setobject (I + 1, argS [I]);} rs = stat.exe cutequery (); If (RS. next () {result = Rs. getObject (1) ;}} catch (sqlexception e) {e. prin Tstacktrace () ;}finally {close (RS, stat, Conn) ;}return result ;}public t executequeryforobject (string SQL, rowmapper <t> RM, object... ARGs) {connection conn = NULL; preparedstatement stat = NULL; resultset rs = NULL; t OBJ = NULL; try {conn = getconnection (); stat = Conn. preparestatement (SQL); For (INT I = 0; I <args. length; I ++) {stat. setobject (I + 1, argS [I]);} rs = stat.exe cutequery (); If (RS. next () {OBJ = RM. Maprow (RS) ;}} catch (exception e) {e. printstacktrace ();} finally {close (RS, stat, Conn);} return OBJ ;} /*** execute the insert update Delete statement * @ Param SQL insert or update or delte statement * @ return true indicates that success is false indicates failure */Public Boolean executesql (string SQL, object... ARGs) {connection conn = NULL; preparedstatement stat = NULL; try {conn = getconnection (); stat = Conn. preparestatement (SQL );//? For (INT I = 0; I <args. length; I ++) {stat. setobject (I + 1, argS [I]);} int rows = stat.exe cuteupdate (); If (rows> 0) {return true ;}} catch (exception E) {e. printstacktrace ();} finally {close (stat, Conn);} return false ;} /*** release database resources ** @ Param RS * @ Param stat * @ Param conn */Public void close (resultset RS, statement stat, connection conn) {try {If (RS! = NULL) {Rs. Close () ;}catch (sqlexception e) {e. printstacktrace () ;}finally {try {If (stat! = NULL) {Stat. Close () ;}catch (sqlexception e) {e. printstacktrace () ;}finally {try {If (Conn! = NULL) {Conn. close () ;}} catch (sqlexception e) {e. printstacktrace () ;}}}/*** release database resources * @ Param stat * @ Param conn */Public void close (statement stat, connection conn) {close (null, stat, Conn );}}

11. rowmapper. Java

package com.kaishengit.util;import java.sql.ResultSet;import java.sql.SQLException;public interface RowMapper<T> {public T mapRow(ResultSet rs) throws SQLException;}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.