Java Web (iv) file upload and download

Source: Internet
Author: User
Tags get ip parent directory save file java web

First, the principle of file upload

1, in TCP/IP, the earliest file upload mechanism is FTP, it is the standard mechanism to send files to the server by the client, but in the JSP use process can not use the FTP method to upload files, which is determined by the JSP operating mechanism.

By setting the method= "POST" enctype= "Multipart/form-data" property for the form element, the data submitted by the form is submitted in binary encoding, and in the servlet that accepts the request, the binary stream is used to obtain the content. You can get the content of the uploaded file, so as to achieve the file upload.

2. Form Enctype Zodiac

1>application/x-www-form-urlencoded

The default encoding is to handle only the Value property values in the form fields, and the values in the form fields that are encoded in this way are treated as URL encodings.

2>multipart/form-data

This encoded form processes the form data in a binary stream, which encapsulates the file contents specified by the file domain into the request parameters.

3>text/plain

This approach is primarily useful for sending messages directly from a form.

Second, the use of smartupload upload components

Smartupload components are easy to use, can easily implement the restrictions of uploading file types, and can easily get the name, suffix, size of the uploaded file. I need to import the jar package using this component, I am using Jspsmartupload.jar.

1. Upload a single file

Upload.htm

<title> File Upload </title>
<body>
<form action= "upload.jsp" method= "post" enctype= "Multipart/form-data" >
Please select file: <input type= "file" name= "pic" >
<input type= "Submit" value= "Upload" >
</form>
</body>

upload.jsp

<%@ page contenttype= "text/html" pageencoding= "Utf-8"%>
<%@ page import= "com.jspsmart.upload.*"%>
<title> File Upload 2</title>
<body>
<%
Smartupload smart=new smartupload ();
Smart.initialize (PageContext);
Smart.upload ();
Smart.save ("Upload");
%>
</body>

Here to note the introduction of the import jar package in the JSP page class file: Above is com.jspsmart.upload.*, why this write, you can use 360 compression to open the jar package file as follows:

Upload represents the folder where files are uploaded, which are created manually with the directory. The upload results are as follows:

2. Mix the forms

If you are uploading a file, the form must be encapsulated, but the form control that uses the Enctype wrapper for other non-file classes cannot be obtained through the request built-in object, which must be obtained through the Getrequest () method of the Smartupload class.

Upload2.htm

<title> File Upload </title>
<body>
<form action= "upload2.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>

upload2.jsp

<%@ page contenttype= "text/html" pageencoding= "Utf-8"%>
<%@ page import= "com.jspsmart.upload.*"%>
<title> File Upload 2</title>
<body>
<%
Smartupload smart=new smartupload (); Instantiating the Smartupload upload component
Smart.initialize (PageContext); Initializing the upload operation
Smart.upload (); Upload Preparation
String name=smart.getrequest (). GetParameter ("uname"); Accept Request Parameters
Smart.save ("Upload"); Save the uploaded file in the Upload folder
%>
</body>

3. Automatic naming for uploaded files

The main purpose is to prevent overwriting files in case of duplicate names. In the following example, the file name takes the IP address + timestamp + three-bit random number

Upload3.htm

<title> File Upload </title>
<body>
<form action= "upload3.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>

upload3.jsp

<%@ page contenttype= "text/html" pageencoding= "Utf-8"%>
<%@ page import= "com.jspsmart.upload.*"%>
<%@ page import= "Kk.upload3.IPTimeStamp"%>
<title> File Upload 3</ Title>
<body>
<%
request.setcharacterencoding ("Utf-8");
Instantiate the Smartupload upload component
Smartupload smart=new smartupload ();
Initialize the upload operation
Smart.initialize (PageContext);
Upload Preparation
Smart.upload ();
Accept the request parameter
String name=smart.getrequest (). GetParameter ("uname");

Iptimestamp its=new Iptimestamp (request.getremoteaddr ());
//Get file suffix name
String ext=smart.getfiles (). GetFile (0). Getfileext ();
Patchwork file name
String filename=its.getiptimerand () + "." +ext;
System.out.println ("file name and suffix ==>" +filename);
//Save file

Smart.getfiles (). GetFile (0). SaveAs (Getservletcontext (). Getrealpath ("/")
+ "upload" + Java.io.file.separator+filename); The

//./represents the current directory; /indicates the directory where the source files are located; /.. /indicates the upper parent directory of the directory where the source file resides, and so on
%>

<%=getservletcontext (). Getrealpath ("/") + "upload" +java.io.file.separator+filename%>


</body>

Iptimestamp.java

Package kk.upload3;
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;
System.out.println ("ip=" +ip);
}

Get IP address + timestamp + three-bit random number
Public String Getiptimerand () {

StringBuffer buf=new StringBuffer ();
if (this.ip!=null) {
/*
* Split operation
* in Java \ represents the escape character \ T and so on, while \ \ represents a backslash instead. Represents a meta-character
* to represent a. You need to use \.
* so "\ \" is represented in the actual compilation.
* */
String s[]=this.ip.split ("\ \");
for (int i=0;i<s.length;i++) {

Not enough three digits to fill 0
Buf.append (This.addzero (s[i],3));
}
}
Get time stamp
Buf.append (This.gettimestamp ());
Random r=new random ();
for (int i=0;i<3;i++) {

Buf.append (R.nextint (10));
}
System.out.println ("File prefix ==>" +buf.tostring ());
return buf.tostring ();
}

private string Addzero (string Str,int len) {

StringBuffer s=new StringBuffer ();
S.append (str);
while (S.length () <len) {
S.insert (0, "0");
}
System.out.println (s);
return s.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 ());
}

}

Operation Result:

Problem: Limit file upload types?

For example, verify the validity of the upload file suffix:

Indicates that only file uploads with a suffix of jpg/gif are allowed.

if (Smart.getfiles (). GetFile (0). GetFileName (). Matches ("^\\w+\\." ( Jpg|gif) ($ ")) {

}

4. Batch Upload

Make the following changes to the upload3.jsp file without changing the other

<%@ page contenttype= "text/html" pageencoding= "Utf-8"%>
<%@ page import= "com.jspsmart.upload.*"%>
<%@ page import= "Kk.upload3.IPTimeStamp"%>
<title> File Upload 3</title>
<body>
<%
Request.setcharacterencoding ("Utf-8");
Smartupload smart=new smartupload ();
Smart.initialize (PageContext);
Smart.upload ();
String name=smart.getrequest (). GetParameter ("uname");
Iptimestamp its=new Iptimestamp (request.getremoteaddr ());
for (int x=0;x<smart.getfiles (). GetCount (); x + +) {
String ext=smart.getfiles (). GetFile (x). Getfileext ();
String Filename=its.getiptimerand () + "." +ext;
Smart.getfiles (). GetFile (x). SaveAs (Getservletcontext (). Getrealpath ("/")
+ "Upload" +java.io.file.separator+filename);
}

%>

</body>

Number of uploaded files: Smart.getfiles (). GetCount ().

Third, the use of fileupload upload components

Java Web (iv) file upload and download

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.