Tips for uploading and downloading files in a web environment using Java

  • 2020-04-01 04:35:31
  • OfStack

Fileupload is very common in web applications, it is very easy to realize the fileupload function in the JSP environment, because there are many fileupload components developed in Java, this article to Commons -fileupload component as an example, add fileupload function for JSP application.

Common - the fileupload component is one of the apache, an open source project, can be downloaded from (link: http://jakarta.apache.org/commons/fileupload/).

With this component, you can upload one or more files at a time and limit the file size.

After downloading the zip package, copy the commons-fileupload-1.0.jar to tomcat webapps under your webappweb-inflib, the directory does not exist, please create the directory.

Create a new servlet: upload.java for file Upload:


import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
import org.apache.commons.fileupload.*; 
public class Upload extends HttpServlet {
private String uploadPath = "C:upload"; //Directory of uploaded files
private String tempPath = "C:uploadtmp"; //Temporary file directory
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
}
}

In the doPost() method, when the servlet receives a Post request from the browser, the file is uploaded. Here is the sample code:


public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
try {
DiskFileUpload fu = new DiskFileUpload(); 
//Set the maximum file size, in this case 4MB
fu.setSizeMax(4194304); 
//Set the buffer size, in this case 4kb
fu.setSizeThreshold(4096); 
//Set up temporary directory:
fu.setRepositoryPath(tempPath); 

//Get all the files:
List fileItems = fu.parseRequest(request); 
Iterator i = fileItems.iterator(); 
//Process each file in turn:
while(i.hasNext()) {
FileItem fi = (FileItem)i.next(); 
//Get the file name, which includes the path:
String fileName = fi.getName(); 
//User and file information can be recorded here
// ...
//Write to a file with the temporary name a.t.xt and extract the name from fileName:
fi.write(new File(uploadPath + "a.txt")); 
}
}
catch(Exception e) {
//You can jump to the error page
}
}

If you want to read the specified upload folder in the configuration file, you can do this in the init() method:


public void init() throws ServletException {
uploadPath = ....
tempPath = ....
//Folder is automatically created if it does not exist:
if(!new File(uploadPath).isDirectory())
new File(uploadPath).mkdirs(); 
if(!new File(tempPath).isDirectory())
new File(tempPath).mkdirs(); 
}

To compile the servlet, be careful to specify the classpath and be sure to include commons-upload-1.0.jar and tomcatcommonlibservlet-api.jar.

Configure the servlet and use notepad to open your webappweb-infweb.xml tomcatwebapps and create a new one if you don't have one.

Typical configurations are as follows:


 The < ?xml version="1.0" encoding="ISO-8859-1"? > 
 The < !DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" > 

 The < web-app > 
 The < servlet > 
 The < servlet-name > Upload The < /servlet-name > 
 The < servlet-class > Upload The < /servlet-class > 
 The < /servlet > 

 The < servlet-mapping > 
 The < servlet-name > Upload The < /servlet-name > 
 The < url-pattern > /fileupload The < /url-pattern > 
 The < /servlet-mapping > 
 The < /web-app > 

After configuring the servlet, start tomcat and write a simple HTML test:


 The < form action="fileupload" method="post"
enctype="multipart/form-data" name="form1" > 
 The < input type="file" name="file" > 
 The < input type="submit" name="Submit" value="upload" > 
 The < /form > 

Note that action="fileupload" where fileupload is the url-pattern specified when configuring the servlet.

Here's the code for a prawn:

This Upload is much better than smartUpload. It was created by debugging every byte, unlike smartUpload, which has many bugs.

Call method:


Upload up = new Upload(); 
up.init(request); 

up. uploadFile(); 

Then String[] names = up.getfilename (); Get the file name of the upload, the absolute path of the file should be

SaveDir +"/"+names[I];

Up.getparameter ("field"); Get the uploaded text or up.getparametervalues (" field ")

Gets the values of fields with the same name, such as multiple checkboxes.

Try the others yourself.

Source code is shown below: ____________________________________________________________


package com.inmsg.beans; 
import java.io.*; 
import java.util.*; 
import javax.servlet.*; 
import javax.servlet.http.*; 
public class Upload {
private String saveDir = "."; //The path to save the file
private String contentType = ""; //The document type
private String charset = ""; //Character set
private ArrayList tmpFileName = new ArrayList(); //A data structure that temporarily stores file names
private Hashtable parameter = new Hashtable(); //A data structure that holds parameter names and values
private ServletContext context; //Program context for initialization
private HttpServletRequest request; //An instance of the incoming request object
private String boundary = ""; //Delimiter for memory data
private int len = 0; //The length of bytes actually read from inside each time
private String queryString; 
private int count; //Total number of files uploaded
private String[] fileName; //Array of uploaded file names
private long maxFileSize = 1024 * 1024 * 10; //Maximum file upload bytes;
private String tagFileName = ""; 
public final void init(HttpServletRequest request) throws ServletException {
this.request = request; 
boundary = request.getContentType().substring(30); //Gets an in-memory data delimiter
queryString = request.getQueryString(); 
}
public String getParameter(String s) { //To get the parameter value of the specified field, override request-getparameter (String s)
if (parameter.isEmpty()) {
return null; 
}
return (String) parameter.get(s); 
}
public String[] getParameterValues(String s) { //Used to specify the parameters of the field with the same array, rewrite the request. GetParameterValues (String s)
ArrayList al = new ArrayList(); 
if (parameter.isEmpty()) {
return null; 
}
Enumeration e = parameter.keys(); 
while (e.hasMoreElements()) {
String key = (String) e.nextElement(); 
if ( -1 != key.indexOf(s + "||||||||||") || key.equals(s)) {
al.add(parameter.get(key)); 
}
}
if (al.size() == 0) {
return null; 
}
String[] value = new String[al.size()]; 
for (int i = 0; i  The <  value.length; i++) {
value[i] = (String) al.get(i); 
}
return value; 
}
public String getQueryString() {
return queryString; 
}
public int getCount() {
return count; 
}
public String[] getFileName() {
return fileName; 
}
public void setMaxFileSize(long size) {
maxFileSize = size; 
}
public void setTagFileName(String filename) {
tagFileName = filename; 
}
public void setSaveDir(String saveDir) { //Sets the path to save the upload file
this.saveDir = saveDir; 
File testdir = new File(saveDir); //To ensure that the directory exists, create a new directory if it does not
if (!testdir.exists()) {
testdir.mkdirs(); 
}
}
public void setCharset(String charset) { // Set up the Character set
this.charset = charset; 
}
public boolean uploadFile() throws ServletException, IOException { //The upload method invoked by the user
setCharset(request.getCharacterEncoding()); 
return uploadFile(request.getInputStream()); 
}
private boolean uploadFile(ServletInputStream servletinputstream) throws //The master method for obtaining central storage data
ServletException, IOException {
String line = null; 
byte[] buffer = new byte[256]; 
while ( (line = readLine(buffer, servletinputstream, charset)) != null) {
if (line.startsWith("Content-Disposition: form-data; ")) {
int i = line.indexOf("filename="); 
if (i  > = 0) { //If there is filename= in the description in a delimiter, it is the encoded content of the file
String fName = getFileName(line); 
if (fName.equals("")) {
continue; 
}
if (count == 0 && tagFileName.length() != 0) {
String ext = fName.substring( (fName.lastIndexOf(".") + 1)); 
fName = tagFileName + "." + ext; 
}
tmpFileName.add(fName); 
count++; 
while ( (line = readLine(buffer, servletinputstream, charset)) != null) {
if (line.length()  The < = 2) {
break; 
}
}
File f = new File(saveDir, fName); 
FileOutputStream dos = new FileOutputStream(f); 
long size = 0l; 
while ( (line = readLine(buffer, servletinputstream, null)) != null) {
if (line.indexOf(boundary) != -1) {
break; 
}
size += len; 
if (size  >  maxFileSize) {
throw new IOException(" File more than " + maxFileSize + " byte !"); 
}
dos.write(buffer, 0, len); 
}
dos.close(); 
}
else { //Otherwise it is the content of the field encoding
String key = getKey(line); 
String value = ""; 
while ( (line = readLine(buffer, servletinputstream, charset)) != null) {
if (line.length()  The < = 2) {
break; 
}
}
while ( (line = readLine(buffer, servletinputstream, charset)) != null) {
if (line.indexOf(boundary) != -1) {
break; 
}
value += line; 
}
put(key, value.trim(), parameter); 
}
}
}
if (queryString != null) {
String[] each = split(queryString, "&"); 
for (int k = 0; k  The <  each.length; k++) {
String[] nv = split(each[k], "="); 
if (nv.length == 2) {
put(nv[0], nv[1], parameter); 
}
}
}
fileName = new String[tmpFileName.size()]; 
for (int k = 0; k  The <  fileName.length; k++) {
fileName[k] = (String) tmpFileName.get(k); //Dump the temporary file name from the ArrayList into the data for the user to call
}
if (fileName.length == 0) {
return false; //If the fileName data is empty, no file has been uploaded
}
return true; 
}
private void put(String key, String value, Hashtable ht) {
if (!ht.containsKey(key)) {
ht.put(key, value); 
}
else { //If you already have a KEY with the same name, change the name of the current KEY, and be careful not to form a KEY with the same name
try {
Thread.currentThread().sleep(1); //In order not to produce two identical keys in the same ms
}
catch (Exception e) {}
key += "||||||||||" + System.currentTimeMillis(); 
ht.put(key, value); 
}
}

private String readLine(byte[] Linebyte,
ServletInputStream servletinputstream, String charset) {
try {
len = servletinputstream.readLine(Linebyte, 0, Linebyte.length); 
if (len == -1) {
return null; 
}
if (charset == null) {
return new String(Linebyte, 0, len); 
}
else {
return new String(Linebyte, 0, len, charset); 
}
}
catch (Exception _ex) {
return null; 
}
}
private String getFileName(String line) { //Separate the file name from the description string
if (line == null) {
return ""; 
}
int i = line.indexOf("filename="); 
line = line.substring(i + 9).trim(); 
i = line.lastIndexOf(""); 
if (i  The <  0 || i  > = line.length() - 1) {
i = line.lastIndexOf("/"); 
if (line.equals("""")) {
return ""; 
}
if (i  The <  0 || i  > = line.length() - 1) {
return line; 
}
}
return line.substring(i + 1, line.length() - 1); 
}
private String getKey(String line) { //Separate the field name from the description string
if (line == null) {
return ""; 
}
int i = line.indexOf("name="); 
line = line.substring(i + 5).trim(); 
return line.substring(1, line.length() - 1); 
}
public static String[] split(String strOb, String mark) {
if (strOb == null) {
return null; 
}
StringTokenizer st = new StringTokenizer(strOb, mark); 
ArrayList tmp = new ArrayList(); 
while (st.hasMoreTokens()) {
tmp.add(st.nextToken()); 
}
String[] strArr = new String[tmp.size()]; 
for (int i = 0; i  The <  tmp.size(); i++) {
strArr[i] = (String) tmp.get(i); 
}
return strArr; 
}
}
 Downloading is actually very simple, as long as the following processing, there will be no problems. 
public void downLoad(String filePath,HttpServletResponse response,boolean isOnLine)
throws Exception{
File f = new File(filePath); 
if(!f.exists()){
response.sendError(404,"File not found!"); 
return; 
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f)); 
byte[] buf = new byte[1024]; 
int len = 0; 
response.reset(); //It is very important
if(isOnLine){ //Online open mode
URL u = new URL("file:///"+filePath); 
response.setContentType(u.openConnection().getContentType()); 
response.setHeader("Content-Disposition", "inline; filename="+f.getName()); 
//The file name should be encoded as utf-8
}
else{ //Pure download
response.setContentType("application/x-msdownload"); 
response.setHeader("Content-Disposition", "attachment; filename=" + f.getName()); 
}
OutputStream out = response.getOutputStream(); 
while((len = br.read(buf))  > 0)
out.write(buf,0,len); 
br.close(); 
out.close(); 
}

Related articles: