Jsp users upload profile pictures, upload pictures, and upload attachment code

Source: Internet
Author: User
Tags file upload temporary file storage versions

Jsp Tutorial: Upload avatar, upload image, and upload attachment code by email


2. Implementation of page forms
There are two differences between File upload forms and normal forms.

1) file upload field <input type = "file"/>

2) the enctype attribute of form needs to be specified as multipart/form-data

3. Server-side resolution request
In Servlet, the request. getInputStream is used to obtain the form Upload data, and the data is sent in segments.

Because it is difficult to write a program for parsing, we can use the open-source component Commons-fileupload developed by Apache.

Import the jar package Commons-fileupload and Commons-io

4. Process the file upload program in UploadServlet
// 1. Create a factory class

DiskFileItemFactory factory = new DiskFileItemFactory ();

// 2. Create a FileUpload object

ServletFileUpload upload = new ServletFileUpload (factory );

// 3. Determine whether it is an upload form

Boolean B = upload. isMultipartContent (request );

If (! B ){

// Not file Upload

Request. setAttribute ("message", "Sorry, not a file upload form! ");

Request. getRequestDispatcher ("/message. jsp"). forward (request, response );

Return;

}

// A File upload form

// 4. Parse the request to obtain the FileItem

List <FileItem> fileitems = upload. parseRequest (request );

// 5. Traverse the set

For (FileItem item: fileitems ){

// Determine if it is a common field

If (item. isFormField ()){

String name = item. getFieldName ();

String value = item. getString ();

// Manually converted

Value = new String (value. getBytes ("iso-8859-1"), "UTF-8 ");

System. out. println (name + "=" + value );

} Else {

// File upload field

// Get the file name

String filename = item. getName ();

System. out. println (filename );

Filename = filename. substring (filename. lastIndexOf ("") + 1 );

   

System. out. println (filename );

// Create a file

ServletContext context = getServletContext ();

String dir = context. getRealPath ("WEN-INF/upload ");

File file = new File (dir, filename );

File. createNewFile ();

   

// Get the stream and read the data into the file

InputStream in = item. getInputStream ();

FileOutputStream fos = new FileOutputStream (file );

   

Int len;

Byte [] buffer = new byte [1024];

While (len = in. read (buffer)> 0)

Fos. write (buffer, 0, len );

Fos. close ();

In. close ();

Item. delete (); // delete a temporary file

}

II. File upload handling details
1. Chinese garbled characters
1) the file name is garbled in Chinese. Solution: Tell the file upload component how to decode the file name.

ServletUpload. setCharacterEncoding ("UTF-8 ");

Request. setCharacterEncoding ("UTF-8 ");

    

2) Chinese garbled characters in common fields

Fileitem. getString ("UTF-8 ");

2. Temporary files
For large files that cannot be cached in the memory, they must be cached to the hard disk. To facilitate management, we need to set a temporary file storage directory.

// Set the storage location of temporary files

Factory. setRepository (new File ("d:/temp "));

After the file is uploaded, you must delete the temporary file. Otherwise, two files will be uploaded to the server.

// Note: you must first disable the stream; otherwise, temporary files cannot be deleted.

Out. close ();

In. close ();

// Delete a temporary file

Fileitem. delete ();

3. File storage directory
1) The Directory needs to be hidden and direct access to the outside world is prohibited.

2) ensure that the file name is unique.

3) files should be stored in different directories.

3. Upload progress bar
1. Implement progress monitoring
To monitor the file upload progress, add a ProgressListener to the FileUpload object.

Process progress-related data in the upload method

Upload. setProgressListener (new ProgressListener (){

Long num = 0;

Public void update (long bytesRead, long contentLength, int items ){

      

Long progress = bytesRead * 100/contentLength;

If (progress = num)

Return;

Num = progress;

System. out. println ("Upload progress:" + progress + "% ");

      

// Request. getSession (). setAttribute ("progress", progress );

        }

});

2. Display the progress on the jsp page
Lab:

1) use iframe to send a request, request a Servlet, return a response in the Servlet, and send an auto-increment num

At this time, iframe will not stop trying to send requests to the Servlet.

2) after clicking the file upload button, iframe immediately stops refreshing until the upload is complete and the page jumps to the new page.

3) to observe the experiment results, set form target to iframe, and UploadServlet sends back the uploaded results.

4) the cause of the above problem is that the browser does not support multithreading and can only send one request to the server at the same time,

This access method is synchronous access.

5) to implement progress access in iframe while uploading files, the IE browser needs to perform asynchronous interaction with the server.

In this case, the XMLHttpRequest object is required.

In webpage effects, XMLHttpRequest objects can be directly used for asynchronous communication with the server.

There are two ways to obtain the XmlHttpRequest object:

Ie7 or later versions

Var xhr = null;

If (window. XMLHttpRequest)

Xhr = new XMLHttpRequest ();

Ie7 or earlier versions

If (window. ActiveXObject)

Xhr = new ActiveXObject ("Microsoft. XMLHTTP ");

      

After obtaining the object, you must call the open method to enter the request address.

Pay attention to the request method, address input, and must be set to true to specify asynchronous access to this address

Xhr. open ("get", "/upload/servlet/UploadServlet", false)

      

// Call the send method to send the request. The post method needs to send the message body, and the get method does not need to directly input a null value.

Xhr. send (null );

      

// Access The responseText attribute to obtain the data returned by the Servlet.

Document. write (xhr. responseText );

IV. api methods
1. DiskFileItemFactory object
Set the buffer size, in bytes. The default value is 10 kB.

Factory. setSizeThreshold (1000 );

Set the temporary file storage directory

Factory. setRepository (file );

2. ServletFileUpload object
Determine whether it is a file upload form

Boolean B = upload. isMultipartContent (request );

Parse request object

List <FileItem> list = upload. parseRequest (request );

Sets the maximum value of the uploaded file.

SetFileSizeMax (long fileSizeMax)

Sets the maximum number of uploaded files.

SetSizeMax (long sizeMax)

Set encoding format

SetHeaderEncoding (java. lang. String encoding)

Register progress listener

SetProgressListener (ProgressListener pListener)

3. FileItem object
Obtain the attribute name of the form field.

Item. getFieldName ();

Obtain the value of a common field

Item. getString (charsetName)

Get the file name of the file upload field

Item. getName ()

Obtain the file upload stream

Item. getInputStream ()

  

Notes for file upload:

1. How to set the maximum value of the uploaded file and give the user a friendly prompt when the maximum value is exceeded
Upload. setFileSizeMax (1024*10); // you can specify the maximum value.
When the maximum value is exceeded, a friendly prompt is displayed: capture FileUploadBase. FileSizeLimitExceededException in the program.
If the program throws this exception, it indicates that the file uploaded by the user exceeds the maximum value.
 
 
2. Garbled characters during the upload process
2.1 garbled characters of common input items
Item. getString ("Code Table ")
2.2 garbled characters in uploaded file names
ServletFileUpload. setHeaderEncoding ("Code Table ")
 
3. Security issues of uploaded files
To prevent users from directly uploading files and endangering server security, the program should prohibit users from directly accessing the uploaded files (that is, saving the uploaded files in directories that users cannot directly access)
 
4. Prevent file overwrite (UUID)

5. Archive files (more than 1000 files cannot be stored in one directory)
Use the hash algorithm to generate a directory for saving
 
6. Set the listener to listen on the file upload progress.

Upload. setProgressListener (new ProgressListener (){
Public void update (long arg0, long arg1, int arg2 ){
System. out. println ("currently uploaded" + arg0 + ", total size of currently processed files" + arg1 );
   }
});

7. Deletion of temporary files
After processing each file upload, remember to call the Fileitem. delete method to delete the temporary file.
 
8. Restrict the Upload file type
Determine the suffix of the uploaded file

 

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.