Java uses the smartupload component to upload files

Source: Internet
Author: User
Tags temporary file storage

Java uses the smartupload component to upload files

This article mainly introduces how to use the smartupload component to upload files in java. It compares and analyzes the differences between using components and not using components to upload files. It has some reference value, for more information, see

This example describes how java uses the smartupload component to upload files. Share it with you for your reference. The specific analysis is as follows:

File Upload is a function provided by almost all websites. You can upload files to a specified folder on the server or store them in a database. Here, we mainly describe the smartupload component upload.

Before explaining how to upload a smartupload file, let's take a look at how the upload is completed without using components?

Let's talk a little bit about the Code:

The Code is as follows:

Import java. io .*;
Import java. util .*;
Import javax. servlet. http. HttpServletRequest;
Import org. apache. commons. fileupload. FileItem;
Import org. apache. commons. fileupload. FileUploadException;
Import org. apache. commons. fileupload. disk. DiskFileItemFactory;
Import org. apache. commons. fileupload. servlet. ServletFileUpload;
Public class FileUploadTools {
Private HttpServletRequest request = null; // get the HttpServletRequest object
Private List <FileItem> items = null; // save all uploaded content
Private Map <String, List <String> params = new HashMap <String, List <String> (); // save all parameters
Private Map <String, FileItem> files = new HashMap <String, FileItem> ();
Private int maxSize = 3145728; // The default size of the uploaded file is 3 MB, 3*1024*1024
Public FileUploadTools (HttpServletRequest request, int maxSize,
String tempDir) throws Exception {// transfer the request object, maximum upload limit, and temporary storage directory
This. request = request; // receives the request object
DiskFileItemFactory factory = new DiskFileItemFactory (); // create a disk factory
If (tempDir! = Null) {// determines whether a temporary upload directory is required
Factory. setRepository (new File (tempDir); // you can specify the temporary File storage directory.
}
ServletFileUpload upload = new ServletFileUpload (factory); // create a processing tool
If (maxSize> 0) {// if the upload size limit is greater than 0, use the new settings
This. maxSize = maxSize;
}
Upload. setFileSizeMax (this. maxSize); // set the maximum upload size to 3 MB, 3*1024*1024
Try {
This. items = upload. parseRequest (request); // receives all content
} Catch (FileUploadException e ){
Throw e; // throw an exception
}
This. init (); // Initialization
}
Private void init () {// initialization parameter, which distinguishes between common parameters and uploaded files
Iterator <FileItem> iter = this. items. iterator ();
IPTimeStamp its = new IPTimeStamp (this. request. getRemoteAddr ());
While (iter. hasNext () {// retrieve each upload item in sequence
FileItem item = iter. next (); // retrieves each uploaded file
If (item. isFormField () {// determines whether it is a common text Parameter
String name = item. getFieldName (); // obtain the form name.
String value = item. getString (); // obtain the content of the form.
List <String> temp = null; // Save the content
If (this. params. containsKey (name) {// determines whether the content has been stored
Temp = this. params. get (name); // If yes, retrieve
} Else {// does not exist
Temp = new ArrayList <String> (); // reopens the List Array
}
Temp. add (value); // set content to the List Array
This. params. put (name, temp); // add content to Map
} Else {// determine whether it is a file component
String fileName = its. getIPTimeRand ()
+ "." + Item. getName (). split ("\.") [1];
This. files. put (fileName, item); // save all uploaded files
}
}
}
Public String getParameter (String name) {// get a parameter
String ret = null; // Save the returned content
List <String> temp = this. params. get (name); // retrieves content from the set
If (temp! = Null) {// determines whether the content can be retrieved based on the key
Ret = temp. get (0); // retrieve the content
}
Return ret;
}
Public String [] getParameterValues (String name) {// obtain a set of upload content
String ret [] = null; // Save the returned content
List <String> temp = this. params. get (name); // retrieve the content based on the key
If (temp! = Null) {// avoid NullPointerException
Ret = temp. toArray (new String [] {}); // convert the content into a String Array
}
Return ret; // returns a string array.
}
Public Map <String, FileItem> getUploadFiles () {// retrieve all uploaded files
Return this. files; // obtain all uploaded files.
}
Public List <String> saveAll (String saveDir) throws IOException {// save all files and return the file name. All exceptions are thrown.
List <String> names = new ArrayList <String> ();
If (this. files. size ()> 0 ){
Set <String> keys = this. files. keySet (); // obtain all keys.
Iterator <String> iter = keys. iterator (); // instantiate an Iterator object
File saveFile = null; // defines the saved File
InputStream input = null; // defines the input stream of the file, used to read the source file
OutputStream out = null; // defines the output stream of the file, used to save the file
While (iter. hasNext () {// cyclically retrieve each uploaded file
FileItem item = this. files. get (iter. next (); // extracts each file in sequence
String fileName = new IPTimeStamp (this. request. getRemoteAddr ())
. GetIPTimeRand ()
+ "." + Item. getName (). split ("\.") [1];
SaveFile = new File (saveDir + fileName); // splice the new path
Names. add (fileName); // Save the name of the generated file
Try {
Input = item. getInputStream (); // get InputStream
Out = new FileOutputStream (saveFile); // defines the output stream to save the file
Int temp = 0; // receives each byte
While (temp = input. read ())! =-1) {// read the content in sequence
Out. write (temp); // Save the content
}
} Catch (IOException e) {// catch an exception
Throw e; // throws an exception
} Finally {// perform the final close operation
Try {
Input. close (); // close the input stream
Out. close (); // close the output stream.
} Catch (IOException e1 ){
Throw e1;
}
}
}
}
Return names; // return the name of the generated file.
}
}

 

The above code completes the upload without components.

The following describes smartupload.

Smartupload is a set of upload package developed by www.jspsmart.com, which allows you to easily upload and download files, the smartupload component is easy to use and can easily restrict the types of uploaded files, and can also easily obtain the name, suffix, and size of the uploaded files.

Smartupload is a jar package (smartupload. jar) provided by the system. You can directly put this package under classpath, or directly copy this package to the TOMCAT_HOME \ lib directory.

The following describes how to upload data using components.

Upload a single file:

The Code is as follows:

<Html>
<Head> <title> smartupload component upload </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/> <Body>
<Form action = "smartupload_demo01.jsp" method = "post" enctype = "multipart/form-data">
Image <input type = "file" name = "pic">
<Input type = "submit" value = "Upload">
</Form>
</Body>
</Html>

 

Jsp code:

Smartupload_demo01.jsp

The Code is as follows:

<% @ Page contentType = "text/html" pageEncoding = "UTF-8" %>
<% @ Page import = "com. jspsmart. upload. *" %>
<Html>
<Head> <title> smartupload component upload 01 </title>  

<Body>
<%
SmartUpload smart = new SmartUpload ();
Smart. initialize (pageContext); // initialize the upload operation
Smart. upload (); // upload preparation
Smart. save ("upload"); // save the file
Out. print ("uploaded successfully ");
%>

</Body>
</Html>

 

Batch upload:

Html file

 

The Code is as follows:

<Html>
<Head> <title> smartupload component upload 02 </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/> <Body>
<Form action = "smartupload_demo02.jsp" method = "post" enctype = "multipart/form-data">
Image <input type = "file" name = "pic1"> <br>
Image <input type = "file" name = "pic2"> <br>
Image <input type = "file" name = "pic3"> <br>
<Input type = "submit" value = "Upload">
<Input type = "reset" value = "reset">
</Form>
</Body>
</Html>

 

Jsp code

Smartupload_demo02.jsp

The Code is as follows:

<% @ Page contentType = "text/html" pageEncoding = "UTF-8" %>
<% @ Page import = "com. jspsmart. upload. *" %>
<% @ Page import = "com. zhou. study. *" %>
<Html>
<Head> <title> smartupload component upload 02 </title> <Body>
<%
SmartUpload smart = new SmartUpload ();
Smart. initialize (pageContext); // initialize the upload operation
Smart. upload (); // upload preparation
String name = smart. getRequest (). getParameter ("uname ");
IPTimeStamp its = new IPTimeStamp ("192.168.1.1"); // obtain the Client IP Address
For (int x = 0; x <smart. getFiles (). getCount (); x ++ ){
String ext = smart. getFiles (). getFile (x). getFileExt (); // extension name
String fileName = its. getIPTimeRand () + "." + ext;
Smart. getFiles (). getFile (x ). saveAs (this. getServletContext (). getRealPath ("/") + "upload" + java. io. file. separator + fileName );
}
Out. print ("uploaded successfully ");
%>
</Body>
</Html>

 

Note: The upload folder can be created in the TOMCAT_HOME/project directory to run properly!

After a simple upload operation, the uploaded file name is the original file name. You can rename the tool class.

Attached is the tool class for renaming.

The Code is as follows:

Package com. zhou. study;
Import java. text. SimpleDateFormat;
Import java. util. Date;
Import java. util. Random;
Public class IPTimeStamp {
Private SimpleDateFormat sdf = null;
Private String ip = null;
Public IPTimeStamp (){
}
Public IPTimeStamp (String ip ){
This. ip = ip;
}
Public String getIPTimeRand (){
StringBuffer buf = new StringBuffer ();
If (this. ip! = Null ){
String s [] = this. ip. split ("\\.");
For (int I = 0; I <s. length; I ++ ){
Buf. append (this. addZero (s [I], 3 ));
}
}
Buf. append (this. getTimeStamp ());
Random r = new Random ();
For (int I = 0; I <3; I ++ ){
Buf. append (r. nextInt (10 ));
}
Return buf. toString ();
}
Public String getDate (){
This. sdf = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss. SSS ");
Return this. sdf. format (new Date ());
}
Public String getTimeStamp (){
This. sdf = new SimpleDateFormat ("yyyyMMddHHmmssSSS ");
Return this. sdf. format (new Date ());
}
Private String addZero (String str, int len ){
StringBuffer s = new StringBuffer ();
S. append (str );
While (s. length () <len ){
S. insert (0, "0 ");
}
Return s. toString ();
}
Public static void main (String args []) {
System. out. println (new IPTimeStamp (). getIPTimeRand ());
}
}

 

Attached usage:

The Code is as follows:

<Html>
<Head> <title> smartupload file rename </title>
<Meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8"/> <Body>
<Form action = "smartupload_demo03.jsp" method = "post" enctype = "multipart/form-data">
Name <input type = "text" name = "uname"> <br>
Photo <input type = "file" name = "pic"> <br>
<Input type = "submit" value = "Upload">
<Input type = "reset" value = "reset">
</Form>
</Body>
</Html>

 

Jsp code:

Smartupload_demo03.jsp

The Code is as follows:

<% @ Page contentType = "text/html" pageEncoding = "UTF-8" %>
<% @ Page import = "com. jspsmart. upload. *" %>
<% @ Page import = "com. zhou. study. *" %>
<Html>
<Head> <title> smartupload </title> <Body>
<%
SmartUpload smart = new SmartUpload ();
Smart. initialize (pageContext); // initialize the upload operation
Smart. upload (); // upload preparation
String name = smart. getRequest (). getParameter ("uname ");
String str = new String (name. getBytes ("gbk"), "UTF-8"); // garbled characters are generated during value transfer. Transcoding
IPTimeStamp its = new IPTimeStamp ("192.168.1.1"); // obtain the Client IP Address
String ext = smart. getFiles (). getFile (0). getFileExt (); // extension name
String fileName = its. getIPTimeRand () + "." + ext;
Smart. getFiles (). getFile (0 ). saveAs (this. getServletContext (). getRealPath ("/") + "upload" + java. io. file. separator + fileName );
Out. print ("uploaded successfully ");
%>

 

<H2> name: <% = str %>
</Body>
</Html>

 

I hope this article will help you with jsp program design.

Related Article

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.