Upload and download struts2 files

Source: Internet
Author: User

I haven't written about struts2 upload and download before, but I just know how to do it. Recently I used it in the project. It happened to catch up. I encountered some problems in the encoding process, such as file upload type and Chinese garbled characters, compatibility issues, but all of them are solved one by one. The following is an example of your code. For future reference...

I also hope this article will help many of my friends avoid detours!

1. File Upload

The first is the jsp page code.

Define an upload tag on the jsp page

1 <tr> 2 <td align = "right" bgcolor = "# F5F8F9"> <B> Appendix: </B> </td> 3 <td bgcolor = "# FFFFFF"> 4 <input type = "file" name = "upload"/> 5 </td> 6 <td bgcolor = "# FFFFFF"> & nbsp; </td> 7 </tr>

The other attributes defined in BaseAction are omitted (you can also define them in your own Action and change the access modifier)

1/** 2 * Action base class 3 **/4 public class BaseAction extends ActionSupport {5 6 protected List <File> upload; 7 protected List <String> uploadContentType; // file type 8 protected List <String> uploadFileName; // file name 9 protected String savePath; // save path 10 11}

Then there is an upload method in the Action. The Code is as follows:

1/** 2*8. upload Attachment 3 * @ param upload 4 */5 public void uploadAccess (List <File> upload) {6 try {7 if (null! = Upload) {8 for (int I = 0; I <upload. size (); I ++) {9 String path = getSavePath () + "\" + getUploadFileName (). get (I); 10 System. out. println (path); 11 item. setAccessory (getUploadFileName (). get (I); 12 13 FileOutputStream fos = new FileOutputStream (path); 14 FileInputStream FD = new FileInputStream (getUpload (). get (I); 15 byte [] buffer = new byte [1024]; 16 int len = 0; 17 while (len = Fi. read (buffer) )> 0) {18 fos. write (buffer, 0, len); 19} 20. close (); 21 fos. close (); 22} 23} 24} catch (Exception e) {25 logger. error ("An error occurred while uploading attachments. ", E); 26} 27}

Next is my struts2.xml file.

 1 <action name="itemRDAction_*" class="itemRDAction" method="{1}"> 2      <param name="savePath">e:\upload</param> 3      <interceptor-ref name="defaultStack"> 4            <param name="fileUpload.allowedTypes"> 5                application/octet-stream,image/pjpeg,image/bmp,image/jpg,image/png,image/gif,image/jpeg,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/vnd.ms-excel 6            </param> 7            <param name="fileUpload.maximumSize">8000000</param> 8      </interceptor-ref> 9      <result name="show_item_rd_upd">  /WEB-INF/jsp/page_item/updItem_rd.jsp</result>10      <result name="show_item_rd_list"> /WEB-INF/jsp/page_item/listItem_rd.jsp</result>11      <result name="show_item_rd_push"> /WEB-INF/jsp/page_item/pushItem_rd.jsp</result>12 </action>

SavePath is the storage path, and fileUpload. allowedTypes is used to restrict the size of the file to be uploaded.

2. File Download

The first is the download link on the page.

1 <tr> 2 <td width = "20%" align = "right" bgcolor = "# F5F8F9"> <B> attachment: </B> </td> 3 <td width = "40%" bgcolor = "# FFFFFF"> 4 <div style = "width: 355px; float: left; ">$ {item. accessory} </div> 5 <c: if test = "$ {! Empty item. accessory} "> 6 <div class =" btn_img "style =" float: left; "> <a style =" color: black; text-decoration: none; "href =" download. action? Filename =$ {item. accessory} "> download </a> </div> 7 </c: if> 8 </td> 9 <td width = "40%" bgcolor = "# FFFFFF"> & nbsp; </td> 10 </tr>

The code for DownloadAction is as follows:

1/** 2 * DownloadAction 3*4 * @ author zhaoxz 5*6 */7 @ Controller ("downloadAction") 8 @ Scope ("prototype ") 9 public class DownloadAction extends BaseAction {10 11/** 12*13 */14 private static final long serialVersionUID =-4278687717124480968L; 15 16 private static Logger logger = Logger. getLogger (DownloadAction. class); 17 18 private String filename; 19 private InputStream inputStream; 20 private String savePath; 21 private String mimeType; 22 23 public InputStream getInputStream () {24 try {25 String path = getSavePath () + "//" + new String (filename. getBytes ("ISO8859-1"), "UTF-8"); 26 System. out. println (path); 27 mimeType = ServletActionContext. getServletContext (). getMimeType (path) + "; charsets = UTF-8"; 28 inputStream = new FileInputStream (path); 29 String agent = request. getHeader ("USER-AGENT"); 30 System. out. println (agent); 31 if (null! = Agent) {32 if (-1! = Agent. indexOf ("Firefox") {// Firefox33 mimeType = mimeType. replace ("UTF-8", "ISO8859-1"); 34} else {// IE7 + Chrome35 System. out. println ("IE, Chrome"); 36 filename = new String (filename. getBytes ("ISO8859-1"), "UTF-8"); 37 filename = java.net. URLEncoder. encode (filename, "UTF-8"); 38} 39} 40} catch (Exception e) {41 logger. error ("An error occurred while downloading file information. ", E); 42} 43 if (null = inputStream) {44 System. out. println ("getResource error"); 45} 46 return inputStream; 47} 48 49 public void setInputStream (InputStream inputStream) {50 this. inputStream = inputStream; 51} 52 53 @ Override54 public String execute () throws Exception {55 return SUCCESS; 56} 57 58/************************** get set ****** * **********************/59 public String getSavePath () {60 return this. savePath; 61} 62 63 public void setSavePath (String savePath) {64 this. savePath = savePath; 65} 66 67 public String getFilename () {68 return filename; 69} 70 71 public void setFilename (String filename) {72 this. filename = filename; 73} 74}

Then there is its struts2.xml file:

1 <action name="download" class="downloadAction">2     <param name="savePath">E:/upload</param>3     <result type="stream">4           <param name="contentType">${mimeType}</param>5           <param name="contentDisposition">attachment;filename="${filename}"</param>6           <param name="inputName">inputStream</param>7     </result>8 </action>

When downloading the code, pay attention to the encoding format. It will be okay. I hope it will help you! I am too young to be a little white man... I want to learn a lot of things. Please express your understanding if you need any improvement! Thank you.

 

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.