Java in the implementation of file upload download three solutions (recommended) _java

Source: Internet
Author: User
Tags constant i18n readline

Java file upload and file download is a relatively common function of program development, the following through this article to introduce Java in the implementation of file upload download three kinds of solutions, the specific details are shown below;

1th: Java code implementation file upload

Formfile File=manform.getfile ();
String newfilename = null;
String Newpathname=null;
String fileaddre= "/numup";  try {InputStream stream = File.getinputstream ()//read the file into String FilePath = Request.getrealpath (Fileaddre);//Fetch system current path file 
File1 = new File (filePath);//Added the function ((File) file1) to create the directory automatically. mkdir ();
NewFileName = System.currenttimemillis () + file.getfilename (). substring (File.getfilename (). LastIndexOf ('. '));
Bytearrayoutputstream BAOs = new Bytearrayoutputstream ();
OutputStream BOS = new FileOutputStream (FilePath + "/" + NewFileName);
newpathname=filepath+ "/" +newfilename;
System.out.println (Newpathname);
Create an output stream System.out.println (filepath+ "/" +file.getfilename ()) of an uploaded file;
int bytesread = 0;
byte[] buffer = new byte[8192];
while ((bytesread = stream.read (buffer, 0, 8192))!=-1) {bos.write (buffer, 0, bytesread);//write file to server} bos.close ();
Stream.Close (); catch (FileNotFoundException e) {e.printstacktrace ();} catch (IOException e) {e.printstacktrace ();}

Implement file upload on 2nd: JSP page

Package com.vogoal.util;
Import Java.io.BufferedOutputStream;
Import Java.io.File;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.text.SimpleDateFormat;
Import java.util.ArrayList;
Import Java.util.Date;
Import java.util.Hashtable;
Import Javax.servlet.ServletInputStream;
Import Javax.servlet.http.HttpServletRequest; public class Jspfileupload {/** Request object/private HttpServletRequest request = null;/** the path to upload file * * Private String UPL
Oadpath = null;
/** the size of bytes per read * * private static int bufsize = 1024 * 8;
/** Storage Parameters Hashtable * * Private Hashtable paramht = new hasptable ();
/** stores uploaded file name ArrayList/private ArrayList Updfilearr = new ArrayList ();
/** * Set Request object. * @param request * HttpServletRequest Request object/public void Setrequest (HttpServletRequest request) {this.request =
Request
/** * Set File upload path.
* @param path * User-specified file upload paths. */public void Setuploadpath (String path) {this.uploadpath = path;}/** * File upload processing main program. B * * @return int operationResult 0 file operation succeeded; 1 Request object does not exist.
2 no Set file save path or file save path is incorrect, 3 * No correct enctype;4 file operation exception is set.
* * public int process () {int status = 0;////////() Check for request object, upload path, and enctype before file is uploaded.
Status = PreCheck ();
Returns an error code when an error occurs.
if (status!= 0) return status; try {//parameter or filename u string name = NULL;//parameter value String value = NULL;//Read stream is a file's flag bit Boolean fileflag = false;//
The file to store.
File tmpfile = null;
The name of the uploaded file String fName = null;
FileOutputStream BAOs = null;
Bufferedoutputstream BOS = NULL;
Storage parameter Hashtable paramht = new Hashtable ();
Updfilearr = new ArrayList ();
int rtnpos = 0;
Byte[] buffs = new byte[bufsize * 8];
Obtain ContentType String ContentType = Request.getcontenttype ();
int index = Contenttype.indexof ("boundary=");
String boundary = "--" + contenttype.substring (index + 9);
String endboundary = boundary + "--";
Gets the stream from the request object.
ServletInputStream sis = Request.getinputstream (); Read 1-line while (Rtnpos = Sis.readline (buffs, 0, Buffs.length))!=-1) {string strbuff = new String (buffs, 0, Rtnpos);  Reads 1 rows of data n if (Strbuff.startswith (boundary)) {if (name!= null && name.trim (). Length () > 0) {if (Fileflag) {Bos.flush (); Baos.close (); Bos.close (); baos = null; BOS = NULL; Updfilearr.add (fName);} else {Object obj = paramht.g
ET (name);
ArrayList al = new ArrayList ();
if (obj!= null) {Al = (ArrayList) obj;} al.add (value);
System.out.println (value);
Paramht.put (name, AL);
} name = new String ();
Value = new String ();
Fileflag = false;
FName = new String ();
Rtnpos = Sis.readline (buffs, 0, buffs.length); if (Rtnpos!=-1) {Strbuff = new String (buffs, 0, Rtnpos); if (Strbuff.tolowercase (). StartsWith ("Content-disposition:fo Rm-data;  ")) {int nindex = Strbuff.tolowercase (). IndexOf (" name=\ "); int nlastindex = Strbuff.tolowercase (). IndexOf (" \ ", nindex
+ 6);
Name = strbuff.substring (nindex + 6, nlastindex);
int findex = Strbuff.tolowercase (). IndexOf ("filename=\"); if (Findex!=-1) {Fileflag = true; int flastindex = Strbuff.tolowercase (). IndexOf ("\"), Findex + 10);
FName = strbuff.substring (Findex +, flastindex);
FName = GetFileName (fName); if (FName = null | | Fname.trim (). Length () = 0) {Fileflag = false; Sis.readline (buffs, 0, buffs.length); Sis.readline (bu
FFS, 0, Buffs.length);
Sis.readline (buffs, 0, buffs.length);
Continue
}else{fName = Getfilenamebytime (fName); Sis.readline (buffs, 0, buffs.length); Sis.readline (buffs, 0, buffs.length);} 
} else if (Strbuff.startswith (endboundary)) {if (name!= null && name.trim (). Length () > 0) {if (Fileflag) {
Bos.flush ();
Baos.close ();
Bos.close ();
BAOs = null;
BOS = NULL;
Updfilearr.add (FName);
else {Object obj = paramht.get (name);
ArrayList al = new ArrayList ();
if (obj!= null) {Al = (ArrayList) obj;} al.add (value);
Paramht.put (name, AL);  }} else {if (Fileflag) {if (BAOs = = NULL && BOS = NULL) {tmpfile = new File (Uploadpath + fName); BAOs = new
FileOutputStream (tmpfile);
BOS = new Bufferedoutputstream (BAOs);
} bos.write (buffs, 0, Rtnpos); Baos.flUsh ();
else {System.out.println ("Test:" + value + "--" + Strbuff);
Value = value + Strbuff;
catch (IOException e) {status = 4;} return status; private int PreCheck () {int errcode = 0; if (request = null) return 1; if (Uploadpath = null | | Uploadpath.trim ().
Length () = 0) return 2;
else{file Tmpf = new file (Uploadpath); if (!tmpf.exists ()) return 2;}
String ContentType = Request.getcontenttype ();
if (Contenttype.indexof ("multipart/form-data") = = 1) return 3;
return errcode;
public string GetParameter (string name) {String value = ' ";
if (name = = NULL | | Name.trim (). Length () = 0) return value; Value = (Paramht.get (name) = null)? "":(
String) ((ArrayList) paramht.get (name)). Get (0);
return value; Public string[] GetParameters (String name) {if (name = = NULL | | | Name.trim (). Length () = 0) return null; if (PARAMHT.G
ET (name) = = NULL) return null;
ArrayList al = (ArrayList) paramht.get (name);
string[] Strarr = new string[al.size ()]; for (int i=0;i<al.size ();i++) Strarr[i] = (String) al.get (i);
return strarr; public int getupdfilesize () {return updfilearr.size ();} public string[] Getupdfilenames () {string[] Strarr = new String
[Updfilearr.size ()];
for (int i=0;i<updfilearr.size (); i++) strarr[i] = (String) updfilearr.get (i);
return strarr; private string GetFileName (string input) {int findex = Input.lastindexof ("\"); if (Findex = = 1) {Findex = Input.lasti
Ndexof ("/"); 
if (Findex = = 1) {return input;}}
input = input.substring (Findex + 1);
return input;
private string Getfilenamebytime (string input) {int index = Input.indexof (".");
Date dt = new Date ();
SimpleDateFormat SDF = new SimpleDateFormat ("Yyyymmddhhmmsssss");
Return input.substring (0,index) + sdf.format (DT) + input.substring (index); }
}

2. Refer to the Java class in the JSP page:

<% @page import= "com.vogoal.util.JspFileUpload"%>
<%
//initialization
jspfileupload Jfu = new Jspfileupload ();
Set Request Object
Jfu.setrequest (request);
Set the uploaded file path
jfu.setuploadpath ("c:\\");
Upload processing
int rtn = jfu.process ();
Gets the value of the other input control parameters in the form
String username = jfu.getparameter ("username");
If there are multiple input controls for the same parameter, return the array
string[] Usernamearr = jfu.getparameters ("username");
Get the name of the uploaded file
string[] Filearr = Jfu.getupdfilenames ();
Get the number of uploaded files, this method is somewhat chicken
int filenumber = Jfu.getupdfilesize ();
The following is the code for the test output.
//OUT.PRINTLN ("parameter:" + username);
OUT.PRINTLN ("parameter size:" + usernamearr.length);
Out.println ("Filearr size:" + filearr.length);
if (Filearr.length > 0)
//out.println ("Filearr 0:" + filearr[0]);
%>

3rd: struts2 Implementation of File upload and download

The first step: Add Commons-fileupload-1.2.1.jar, Commons-io-1.3.2.jar under Web-inf/lib. These two files can be downloaded from the http://commons.apache.org/.

The second step: the form table enctype set to: "Multipart/form-data", as follows:

Java code

public class uploadaction{ 
private file uploadimage//File 
private String uploadimagecontenttype;//file type 
private string uploadimagefilename;//file name 
private string bookname;//title 
private string author;//author 
private string savepath;// 
the Getter/setter method public string upload () of the Save Location//property of the file 
throws exception{ 
// Implement upload Code, I/O operation completes return 
"uploadsuccess"; 
} 

Note: The file field in a form corresponds to three attributes in the action, which are file, file name, file type, name is fixed, filename must be the same as the file name in the form (uploadimage), file name: File +filename, File type: File +contenttype.

Step Fourth: Configure our upload action into struts.xml.

Java code

<action name= "Upload" class= "com.gqy.UploadAction" > 
<param name= "Savepath" >/uploadfile</param > 
<result>/success.jsp</result> 

Note: Specify the Save directory on the server for the uploaded file, and add the appropriate setter and getter methods for defining the Savepath variable in uploadaction to facilitate Struts2 The UploadFile value is assigned to the Savepath property, which means that the Savepath variable to be used in uploadaction must be defined in Uploadaction.

Manual Profile Filter Type

<param name= "Allowtypes" > 
image/bmp,image/png,image/gif,image/jpeg 

manual configuration file size limit

 
 

File filtering using Struts2 File Upload Interceptor

STRUTS2 provides a file upload interceptor-fileupload, by configuring the Interceptor to facilitate the implementation of the upload file filtering.

When you configure the FileUpload interceptor, you can specify two parameters for it:

allowedtypes: Specifies the file types that are allowed to be uploaded, separated by commas (,) between multiple file types.

maximumsize: Specifies the file size that is allowed to be uploaded, in bytes.

Tip: By configuring the FileUpload interceptor, you can easily implement the text filter, when the file filter failure, the system automatically into the input logic view, so you must configure the action named input logical view, in addition, You must also display the Interceptor reference for the action configuration Defaultstack.

Use the Struts2 interceptor to implement file filtering configuration as follows:

<action name= "uploadfileaction" class= "com.actions.UploadFileAction" > 
<interceptor-ref name= " Defaultstack "> 
<!--Configure the file types that are allowed to be uploaded, multiple use", "separate--> 
<param name=" Fileupload.allowedtypes "> 
Image/bmp,image/png,image/gif,image/jpeg,image/jpg 
, Image/x-png, image/pjpeg 
</param> 
<!-- Configure the file size that is allowed to be uploaded, in bytes, in this case: 1MB--> 
<param name= "fileupload.maximumsize" >1048576</param> 
</ interceptor-ref> 
<result name= "input" >/jsp/oneFileFileupload.jsp</result> 
<result Name= "Success" >/jsp/result.jsp</result> 

When the user upload failed, need to have a certain hint information. In Struts2, you can use the <s:fielderror/> tab to output the error message to the page.

Note: to use the STRUTS2 error message, the action class of the uploaded file must inherit Actionsupport, otherwise Struts2 will not provide the output error message function.

We can configure the resource file (. properties) to save the information that is exported to the user.

Struts.messages.eror.file.too.large: When the upload file size exceeds the set value, STRUTS2 will output the message corresponding to the key.

struts.messages.error.content.type.not.allowed: When the upload file type does not meet the set value, STRUTS2 will output the key corresponding to the message.

Struts.messages.error.uploading: When an unknown error occurs while uploading the file, Struts2 will output the corresponding message for the key.

We also have to configure the resource file into the Struts.xml file, then look at our resource file, already contains Chinese, we have to convert it and then configure it to the project.

To set the resource file in Struts.xml:

<constant name= "struts.custom.i18n.resources" value= "messages"/> or
<constant name= " Struts.custom.i18n.resources "value=" Messages_zh_cn "/>

Use the command native2ascii d:\messages.properties d:\messages_zh_CN.properties to convert the original resource file into support.

Note: to remain internationalized, the name suffix of the resource file is: *_zh_cn+ file extension form.

The principle of uploading multiple files is the same as above, but it should be noted that multiple file domains must have the same name attribute names, and that you should use either file [] or list<file> to receive them in the action.

Personally feel that using this way to upload multiple files is not

Very good.

Struts2 for file download

STRUTS2 provides the stream result type, which is specifically used to support the ability to download files. When you specify a stream result type, you configure a inputname parameter that specifies an input stream that is the portal to the downloaded file (that is, the portal is used to implement the file as a streaming download).

To implement a file download action

public class Filedownloadaction implements action{ 
//This property value is specified in the configuration file, Struts2 is injected automatically (that is, assignment), and you need to provide the setter and getter method for the property 
Private String inputpath;//Specifies the full path (pathname + filename) of the file to be downloaded/ 
* Implementation of the downloaded action class should provide a method to return the InputStream instance, which corresponds to the 
<result.../> InputName Property value is targetfile 
* * Public 
InputStream Gettargetfile () throws exception{ return 
Servletactioncontext.getservletcontext (). getResourceAsStream (InputPath); 
} 
The Execute method that handles the user request, which returns the success string public string 
execute () throws exception{return 
"Success"; 
} 

The configuration of the action in the Struts.xml file

<action name= "Download" class= com. Filedownloadaction ">
<!--Specify the location of the downloaded resource-->
<param name=" InputPath ">/uploadfile/demo.txt</ Param>
<!--configuration result type is the result of stream-->
<result name= "Success" type= "Stream" >
<!-- Specifies the file type of the download file-->
<param name= "ContentType" ></param>
<!--Specify the file location of the download file-->
Name= "InputName" >targetFile</param>
<!--Specify how download files are downloaded and when they are saved, filename must have an extension when it is saved. The extension indicates the icon for the download type-->
<param name= "contentdisposition" >
attachment;filename=struts2.txt
< /param>
<!--Specify the buffer size for the download file-->
<param name= "buffersize" >4096</param>
</ Result>
</action>

The above is a small series of Java to introduce the implementation of the file upload download three kinds of solutions, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.