Javaweb implementation of File upload and download examples of detailed _java

Source: Internet
Author: User
Tags create directory file upload to domain

In Web application development, file upload and download function is a very common function, the following through this article to introduce Javaweb implementation file upload and download examples.

For file upload, the browser upload the file in the form of streaming files to the server side, if the direct use of the servlet to obtain upload file input stream and then parse the request parameters inside is more trouble, So generally choose to use the Apache Open Source Tool common-fileupload This file upload component. This common-fileupload upload component jar package can go to the Apache online download, Common-fileupload is dependent on the Common-io this package, so also need to download the package.

I. File upload

JSP upload page

The following considerations are required for uploading components

Form form: method= "POST" enctype= "Multipart/form-data"
belongs to domain: input type= "file" name= "file" size= "50"

These two points are ready to display as follows

<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>

<context-param>
<description>location to store uploaded file</description>
< param-name>file-upload</param-name>
<param-value>
e:\\temp\\
</param-value >
</context-param>

Processing uploaded JSP

<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%> <%@ page import= " Org.apache.commons.fileupload.fileitem,org.apache.commons.fileupload.disk.diskfileitemfactory, Org.apache.commons.fileupload.servlet.ServletFileUpload "%> <%@ page import=" java.io.File "%> <%@ page
Import= "Java.util.Iterator"%> <%@ page import= "java.util.List"%> file file;
int maxfilesize = 5000 * 1024;
int maxmemsize = 5000 * 1024;
ServletContext context = Pagecontext.getservletcontext (); String filePath = Context.getinitparameter ("file-upload")//Get the upload path in the configuration file string contentType = Request.getcontenttype ( //Returns the MIME type of the request body if ((Contenttype.contains ("Multipart/form-data")) {Diskfileitemfactory factory = new
Diskfileitemfactory ()//Create a hard disk based Fileitem Factory.setsizethreshold (maxmemsize);//Set the maximum cache for the hard disk when writing Factory.setrepository (New File ("e:\\temp\\"))//Set the temporary directory used when uploading servletfileupload upload = new Servletfileupload ( Factory);//Create a File upload processor Upload.setsizemax (maxfilesiZe)/Set file upload maximum size, Unit b try{List fileitems = upload.parserequest (request);//parse composite form data, return a Fileitem collection, so you can upload multiple files at once
Iterator i = Fileitems.iterator ();
Out.println (" 



Two. File download

File Download reference solitary Mountain Wolf Blog, write very detailed, directly to use.
Download the basic idea is: first traverse the download directory of all files, and then displayed on the page, the client issued a request to download, server-side response to download.

List all files for download directory:

public class Listfileservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse resp Onse) throws Servletexception, IOException {//Get upload file directory String Uploadfilepath = This.getservletcontext (). Getrealpath ("
/web-inf/upload ");
Store the filename to download map<string,string> filenamemap = new hashmap<string,string> (); Recursively iterates through all the files and directories in the FilePath directory, storing the file names in the Map collection listfile (new file (Uploadfilepath), filenamemap);
File can represent either a file or a directory//map collection to the listfile.jsp page for display request.setattribute ("fileNameMap", fileNameMap);
Request.getrequestdispatcher ("/listfile.jsp"). Forward (request, response); /** * @Method: ListFile * @Description: recursively traverse all files in the specified directory * @param file represents a file, and also represents a file directory * @param map store file name Map set * * * publi c void ListFile (file file,map<string,string> Map) {//If file represents not a file, but a directory if (!file.isfile ()) {//
List all files and directories under this directory file files[] = File.listfiles (); Traversal files[] Array for (File f:files) {//recursive listfile (F,MAP);} else{/** * Processing file name, uploaded file is in the form of uuid_ file name renamed, remove the file nameUuid_ part File.getname (). IndexOf ("_") retrieves the first occurrence of the "_" character in the string, if the file name is similar to: 9349249849-88343-8344_ _ van _ da. avi so File.getname () . substring (File.getname (). IndexOf ("_") +1) after processing, you can get an _ _ every _ da. avi Part/String realname = File.getname (). SUBSTRING (
File.getname (). IndexOf ("_") +1);
File.getname () Gets the original name of the file, which is unique, so it can be used as a key,realname after the name is processed, and may be repeated map.put (File.getname (), realname); } public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {do
Get (request, response); }
}

Here is a brief listfileservlet of the ListFile method, ListFile method is used to list all the files in the directory, ListFile method internal use of recursion, in the actual development, we will certainly create a table in the database, It will store the uploaded file name and the file's specific directory, we can know the file directory through the query table, is not required to use recursive operation, this example is because the database is not used to store uploaded file names and files of the specific storage location, The location of the uploaded file is also used to scatter the storage of the hash algorithm, so, recursion is needed, and in recursion, the acquired filename is stored in a map set that is passed from the outside to the ListFile method, so that all files are stored in the same map collection.

Configuring Listfileservlet in Web.xml files

<servlet>
<servlet-name>ListFileServlet</servlet-name>
<servlet-class> me.gacl.web.controller.listfileservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ListFileServlet</servlet-name>
<url-pattern>/servlet/listfileservlet </url-pattern>
</servlet-mapping>

The listfile.jsp page for the display download file is as follows:

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%> <%
@taglib prefix= "C" uri= "http://" Java.sun.com/jsp/jstl/core "%>
<! DOCTYPE html>
 
 

Implementing File Downloads

Package Me.gacl.web.controller;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;
Import Java.io.OutputStream;
Import Java.net.URLEncoder;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse; public class Downloadservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse resp Onse) throws Servletexception, IOException {//get the filename to download String filename = request.getparameter ("filename");//
23239283-92489-Avatar. avi FileName = new String (filename.getbytes ("iso8859-1"), "UTF-8"); The uploaded files are all stored in subdirectories under the/web-inf/upload directory, String Filesaverootpath=this.getservletcontext (). Getrealpath ("/web-inf/
Upload ");
Locate the file's directory by file name String Path = Findfilesavepathbyfilename (Filename,filesaverootpath);
Get the file that you want to download = filename = new file (path + "\" + fileName); If the file does not exist if (!file.exists ()) {Request.setattribute ("message"), the resource you are downloading has been deleted!! ");
Request.getrequestdispatcher ("/message.jsp"). Forward (request, response);
Return
//process filename String realname = filename.substring (Filename.indexof ("_") +1); Set the response header to control the browser to download the file Response.setheader ("Content-disposition", "attachment;filename=" + urlencoder.encode (Realname, "")
UTF-8 "));
Read the file to be downloaded, save to the file input stream FileInputStream in = new FileInputStream (path + "\" + fileName);
Create output stream OutputStream out = Response.getoutputstream ();
Create buffer byte buffer[] = new byte[1024];
int len = 0;
Loops read the contents of the input stream into the buffer while (len=in.read (buffer) >0) {//output buffer contents to the browser, implementation file download out.write (buffer, 0, Len);//close file input stream
In.close ();
Turn off the output stream out.close (); /** * @Method: Findfilesavepathbyfilename * @Description: To find the path to the file to download by file name and store upload file root directory * @param filename to download * @para M Saverootpath upload file to save the root directory, that is, the/web-inf/upload directory * @return The storage directory of the files to be downloaded/public string findfilesavepathbyfilename (string Filename,string saverootpath) {int hashcode = Filename.hashcode (); int dir1 = hashcode&0xf;//0--15 int dir2 = (Hashco De&0xf0) >>4; 0-15 String dir = saverootpath + "\" + Dir1 + "\" + Dir2;
Upload\2\3 upload\3\5 file = new file (dir);
if (!file.exists ()) {//Create directory File.mkdirs ();} return dir; public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {DoG
ET (request, response); }
}

Configuring Downloadservlet in Web.xml files

<servlet>
<servlet-name>DownLoadServlet</servlet-name>
<servlet-class> me.gacl.web.controller.downloadservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DownLoadServlet</servlet-name>
<url-pattern>/servlet/downloadservlet </url-pattern>
</servlet-mapping>

The above is a small set to introduce the Javaweb to realize the file upload and download the relevant knowledge, I hope to help.

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.