File Upload and Chinese File Download In ext2.0 + struts2 framework

Source: Internet
Author: User
Tags saveform

1. Struts-xml configuration file settings:

<Constant name = "struts. multipart. maxsize" value = "15097152"/> <! -- The maximum number of bytes allowed for the entire request content during file upload is 15 MB -->

 

<! -- Provides the file upload function -->
<Interceptor-ref name = "fileupload"/>

 

<! -- Attachment action -->
<Action name = "attachmentsaction" class = "*. *. Action. attachmentsaction">
<! -- This setting is required. Do not call the file interceptor .. You can see the importance of this in action later --!>

<Interceptor-ref name = "fileuploadstack"/>
<Result type = "JSON"> </result>
</Action>

 

2. Ext page attachment. jsp

<% @ Page Language = "Java" pageencoding = "UTF-8" %>
<HTML>
<Head>

<Title> attachment management </title>

<Link href = "/EXT/resources/CSS/ext-all.css" rel = "stylesheet" type = "text/CSS"/>
<Script language = "JavaScript" type = "text/JavaScript" src = "/EXT/ext-base.js"> </SCRIPT>
<Script language = "JavaScript" type = "text/JavaScript" src = "/EXT/ext-all.js"> </SCRIPT>
<Script language = "JavaScript" type = "text/JavaScript" src = "/EXT/ext-lang-zh_CN.js"> </SCRIPT>

<Script language = "JavaScript" type = "text/JavaScript">

VaR center;
VaR addfrom;
Ext. onready (function (){

Addform = new Ext. formpanel ({
ID: 'addform ',
Fileupload: True,
Frame: True,
Labelwidth: 60,
Bodystyle: 'padding: 5px 5px 0 ',
Labelalign: 'left ',
Items :[{
Border: false,
Layout: 'column ',
Collapsible: True,
Items :[{
Columnwidth: 0.98,
Border: false,
Layout: 'form ',
Defaulttype: 'textfield ',
Items :[

{Fieldlabel: 'file 1', xtype: 'textfield', inputtype: 'file', name: 'upload', CLS: 'nobordertext', anchor: '2016', allowblank: true },
{Fieldlabel: 'digest 1', maxlength: '808080', name: 'description', maxlengthtext: 'the supplier owner's word count cannot exceed 50', anchor: '123 '}
, {Fieldlabel: 'file 2', xtype: 'textfield', inputtype: 'file', name: 'upload', CLS: 'nobordertext', anchor: '2016 '},
{Fieldlabel: 'summary 2', maxlength: '808080', name: 'description', maxlengthtext: 'the supplier owner's word count cannot exceed 50', anchor: '123 '},
{Fieldlabel: 'file 3', xtype: 'textfield', inputtype: 'file', name: 'upload', CLS: 'nobordertext', anchor: '2016 '},
{Fieldlabel: 'summary 3', maxlength: '808080', name: 'description', maxlengthtext: 'the supplier owner's word count cannot exceed 50', anchor: '123 '}
]
}
]
}
],
Buttons :[
{Text: 'true', Handler: saveform },
{Text: 'close', Handler: function (){
Addform. getform (). Reset ();
Window. Close ();
}
}
]
});
Center = new Ext. Panel ({
ID: 'center ',
Region: 'center ',
Border: false,
Autoscroll: True,
Enabletabscroll: True,
Items: [addform]
});
VaR Panel = new Ext. Panel ({
ID: 'panel ',
Layout: 'fit ',
Border: false,
Items: [center]
});

VaR viewport = new Ext. viewport ({
ID: 'viewport ',
Layout: 'fit ',
Autoscroll: True,
Items: [panel]
});

});
 
Function saveform (){
VaR _ url = "/*/attachmentsaction! Saveattachmentsinfo.html ";
Addform. getform (). Submit ({
URL: _ URL,
Method: 'post ',
// Params: {fkid: addform. findbyid ("fkid"). getvalue ()},
// Callback function for successful submission
Success: function (Form, Action ){
If (action. Result. MSG = 'success '){
Addform. getform (). Reset ();
Window. Close ();
} Else if (action. Result. MSG = 'notfile '){
Ext. msg. Alert ('hprompt ',' the uploaded file does not exist! Please try again! ');
} Else if (action. Result. MSG = 'sizelimitexceededexception '){
Ext. msg. Alert ('hprompt ',' the file you uploaded is too large! File cannot exceed 15m ');
}
},
Failure: function (Form, Action ){
Ext. MessageBox. Hide ();
Ext. MessageBox. Alert ('error', action. Result. msg );
Ext. msg. Alert ('error', 'server error. Please try again later! ');
}
});
}
</SCRIPT>
</Head>

<Body>
</Body>
</Html>

3. Java processing page attachmentsaction. Java

{

 

// The name of the file control defined on the ext page .. This is the property provided by struts2.

// You can change it to another name, as long as the upload, uploadfilename, and uploadcontenttype are consistent.

Private list <File> upload = new arraylist <File> ();
Private list <string> uploadfilename = new arraylist <string> ();
Private list <string> uploadcontenttype = new arraylist <string> ();
Private list <string> description = new arraylist <string> ();
Final Static int max_size = 15*1024*1024; // sets the maximum size of the uploaded file to 15 MB.
Final Static string dir = "/Attachments /";

 

.. Omit set. Get Method

 

/**
* Saves multiple attachments objects.
* This section describes how to save a file to a folder on the server .. It is not stored in the database.
* Author by XJ
* @ Return
* @ Throws exception
*/
Public String saveattachmentsinfo () throws exception {

// The current time of the retrieved System
Calendar cal1 = new gregoriancalendar ();
Simpledateformat thedate = new simpledateformat ("yyyy-mm-dd ");
String strdate = thedate. Format (cal1.gettime ());
String year = "2000 ";
String month = "12 ";
If (strdate. Length ()> 9 ){
Year = strdate. substring (0, 4 );
Month = strdate. substring (5, 7 );
}
// Obtain the relative path of the object
String uploaddir = dir + year + "/" + month + "/";
// Obtain the absolute path of the object
String realuploaddir = servletactioncontext. getservletcontext (). getrealpath (uploaddir );
// The Directory to upload to store the directory of the uploaded file
File dirpath = new file (realuploaddir );
If (! Dirpath. exists ()){
Dirpath. mkdirs ();
}
String name = "";
String address = "";
String measurements = "";
String descriptionname = "";
String link = "";
String MSG = "{success: True, MSG: 'failed '}";
If (upload. Size ()> 0 ){
For (INT I = 0; I <upload. Size (); I ++ ){
Boolean isfile = upload. Get (I). exists ();
If (isfile ){
// Save the attachment database information
// Obtain the original file name
Name = uploadfilename. Get (I );
// Get the file suffix
String suffix = "";
If (name! = NULL &&(! Name. Equals (""))){
Attachments. setname (name );
If (name! = NULL &&(! Name. Equals (""))){
Suffix = Name. substring (name. lastindexof ("."), name. Length ());
}
}
// Operate on the database... here we need the record ID as the name of the file to save
Attachments = new attachments ();
String aid = attachmentsmanager. createattachmentsinfo (attachments );
String fileurl = realuploaddir + "/" + aid + suffix;
This. Copy (upload. Get (I), new file (fileurl ));
Link = link + "file name:" + name + "uploaded successfully! /N ";
MSG = "{success: True, MSG: 'success ', link:'" + link + "'}";
} Else {
Link = "the uploaded file does not exist ";
MSG = "{success: True, MSG: 'notfile', link: '" + link + "'}";
}
}
} Else {
Link = "the file is too large ";
MSG = "{success: True, MSG: 'sizelimitexceededexception ', link:'" + link + "'}";
}
Httpservletresponse response = servletactioncontext. getresponse ();
Response. Reset ();
Response. setcontenttype ("text/html; charset = UTF-8 ");
Out = response. getwriter ();
Out. Print (MSG );
Return none;
}
Private void copy (File SRC, file DST) throws exception {
Inputstream in = NULL;
Outputstream out = NULL;
Try {
In = new fileinputstream (SRC );
Out = new fileoutputstream (DST );
Byte [] buffer = new byte [8192];
Int bytesread;
While (bytesread = in. Read (buffer, 0, 8192 ))! =-1 ){
Out. Write (buffer, 0, bytesread );
}
} Catch (exception e ){
E. printstacktrace ();
} Finally {
If (null! = In ){
Try {
In. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
If (null! = Out ){
Try {
Out. Close ();
} Catch (ioexception e ){
E. printstacktrace ();
}
}
}
}

/**
* Download files from the server
* @ Return
* @ Throws exception
*/
Public String downloadfileinfo () throws exception {
Logger.info ("=============== attachmentsaction downloadfileinfo ============== ");
Httpservletrequest Req = servletactioncontext. getrequest ();
This. setsuccess (true );
Httpservletresponse response = servletactioncontext. getresponse ();
Response. Reset ();
String id = Req. getparameter ("ID ");
If (ID! = NULL &&(! Id. Equals (""))){
Attachments attachments = attachmentsmanager. getattachmentsinfobyid (ID );
// Obtain the prefix of the absolute path of the object
String Path = servletactioncontext. getservletcontext (). getrealpath (attachments. getaddress ());
// Get the file suffix
String suffix = "";
If (attachments. getname ()! = NULL &&(! Attachments. getname (). Equals ("")))
Suffix = attachments. getname (). substring (attachments. getname (). lastindexof ("."), attachments. getname (). Length ());
// Obtain the name of the file on the server
String systemfilename = ID + suffix;
// Obtain the absolute path of the file on the server
String realpath = path + "//" + systemfilename;
// When the file name is Chinese
// String downfilename = new string (attachments. getname (). getbytes ("ISO8859-1"), "UTF-8"); // here I don't need to do this conversion
String downfilename = attachments. getname ();
// Set the response header and download and save the file name
Response. setcontenttype ("application/msdownload; charset = UTF-8 ");

// This is the key to solving the problem of downloading a Chinese name file.
Response. setheader ("content-disposition", "attachment; filename =/" "+ java.net. urlencoder. encode (downfilename," UTF-8 "));
// Open the output stream of the file
Bufferedoutputstream = new bufferedoutputstream (response. getoutputstream ());
This. downloadfilefromsystem (realpath, bufferedoutputstream );
}
Return none;
}
 
/**
* Download files from the server
* @ Param realpath
* @ Param bufferedoutputstream
* @ Throws exception
*/
Private void downloadfilefromsystem (string realpath, bufferedoutputstream) throws exception {
Try {
// Open the stream information of the specified file
Fileinputstream = new fileinputstream (realpath );
Int bytesread = 0;
Byte [] buffer = new byte [8192];
While (bytesread = fileinputstream. Read (buffer, 0, 8192 ))! =-1 ){
Bufferedoutputstream. Write (buffer, 0, bytesread );
}
Fileinputstream. Close ();
Bufferedoutputstream. Close ();
} Catch (exception e ){
E. printstacktrace ();
}
}

 

 

}

 

4. Here the commons-fileupload-1.1.1.jar used. Cannot Use commons-fileupload-1.0.jar files .. What we need is that the jar of org. Apache. commons. fileupload. servlet. servletfileupload. 1.0 is not supported ..

We recommend that you do not use both racks.

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.