Java File upload download

Source: Internet
Author: User


The browser in the process of uploading the file as a stream to the server side, generally choose to use the Apache Open Source Tool common-fileupload This file upload component, Common-fileupload relies on the Common-io package, so the development projectneed to import common-fileupload, and Common-io package。

In the save file name, there may be file duplicate overwrite problem, handling such problems many ways, such as to create a separate folder for each upload file, and then save the file, the file name plus UUID to save files.  To make it easier to find files on the server, this article saves the file by modifying the filename.  Server Store file name format: Original filename + "_" + UUID + file extension (e.g. img20140405_ef039b09-ef4d-405e-86b5-bd59604c014e.jpg). Consider file security, save the upload file in the Web-inf\upload directory, the temp directory web-inf/temp.


1 Add a foreground file upload.jsp

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >


Note: The form submission method needs to be set to post submission, setting the Ebctype property value to Multipart/form-data


2 Adding a background processing servlet file Uploadhandleservlet.java

Set URL access path to/uploadhandleservlet

Package Cjr.servlet;import Java.io.file;import Java.io.fileoutputstream;import java.io.ioexception;import Java.io.inputstream;import Java.util.list;import Java.util.uuid;import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.fileupload.fileitem;import Org.apache.commons.fileupload.fileuploadbase;import Org.apache.commons.fileupload.progresslistener;import Org.apache.commons.fileupload.disk.diskfileitemfactory;import Org.apache.commons.fileupload.servlet.servletfileupload;public class Uploadhandleservlet extends HttpServlet { public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { DoPost (request, response);} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// Get uploaded files to save directory, upload files stored in the Web-inf directory, not allow direct access to the outside world, to ensure the security of uploading files string savepath = THIS.GEtservletcontext (). Getrealpath ("/web-inf/upload");//The temporary file that is generated when uploading, save directory string temppath = This.getservletcontext (). Getrealpath ("/web-inf/temp"); File Tmpfile = new file (TempPath), if (!tmpfile.exists ()) {//Create temp directory Tmpfile.mkdir ();} Message prompt String message = "Upload succeeded"; try {//Use Apache File Upload component to process file upload steps://1, create a diskfileitemfactory factory diskfileitemfactory Factory = new Diskfileitemfactory ();//sets the size of the factory buffer, and when the uploaded file size exceeds the size of the buffer, a temporary file is generated to be stored in the specified temporary directory. Factory.setsizethreshold (1024 * 100);//sets the buffer size to 100KB, if not specified, the buffer size defaults to 10kb// Set the Save directory for temporary files generated when uploading factory.setrepository (tmpfile);//2, create a file upload parser servletfileupload upload = new Servletfileupload ( Factory)///Monitor File Upload Progress Upload.setprogresslistener (new Progresslistener () {public void update (long pbytesread, long Pcontentlength,int arg2) {System.out.println ("File size:" + Pcontentlength + ", currently processed:" + pbytesread);/** * File size: 14608, Currently processed: 4096 file size: 14608, currently processed: 7367 * File Size: 14608, currently processed: 11419 file Size: 14608, currently processed: 14608 */}});// Solve the upload file name of the Chinese garbled upload.setheaderencoding ("UTF-8");//3, to determine whether the data submitted isIs the data that uploads the form if (! Servletfileupload.ismultipartcontent (Request)) {//Get data return in traditional way;} Set the maximum size of the uploaded individual file, currently set to 1024*1024*3 bytes, i.e. 3mbupload.setfilesizemax (1024 * 1024 * 3);//Set the maximum number of uploaded files, max = Simultaneous uploading of the maximum value of the size of multiple files is currently set to 20mbupload.setsizemax (1024 * 1024 * 20);//4, using the Servletfileupload parser to parse the uploaded data, the result of the parse is to return a list <FileItem> set, each fileitem corresponds to the entry of a form form @suppresswarnings ("unchecked") list<fileitem> List = Upload.parserequest (request); for (Fileitem item:list) {//If the data encapsulated in Fileitem is a normal input item if (Item.isformfield ()) {String name = Item.getfieldname ();//solve the problem of the normal input data in Chinese garbled string value = Item.getstring ("UTF-8");//value = new String (Value.getbytes (" Iso8859-1 ")," UTF-8 "); SYSTEM.OUT.PRINTLN (name + "=" + value);} else {//If the file name of the uploaded file//Get uploaded is encapsulated in Fileitem, String filename = Item.getname (); SYSTEM.OUT.PRINTLN (filename), if (filename = = NULL | | Filename.trim (). Equals ("")) {continue;} Note: Different browser file names are not the same, some browsers submit the file name is with the path, such as://C:\a\b\1.txt, and some are just simple file name, such as: 1.txt//processing gets to the file name of the uploaded files part of the path, Keep only the filename part of filename = FILENAME.SUbstring (filename.lastindexof ("\ \") + 1);//Gets the input stream of the uploaded file in the item inputstream in = Item.getinputstream ();// Create a file output stream FileOutputStream out = new FileOutputStream (savepath + "\ \" + makefilename (filename));//Create a buffer byte buffer[] = n EW byte[1024];//Determines whether the data in the input stream has been read, the identifier int len = 0;//loop reads the input stream into the buffer, and (len=in.read (buffer)) >0 indicates that the in inside also has the data while (len = In.read (buffer)) > 0) {//use FileOutputStream output stream to write buffer data to the specified directory (savepath + "\ \"//+ makefilename (filename)) Among the out.write (buffer, 0, Len);} Turn off input stream in.close ();//Close output stream out.close (); Delete temporary files generated when processing file uploads item.delete (); }}} catch (Fileuploadbase.filesizelimitexceededexception e) {e.printstacktrace (); Request.setattribute ("Message", " Single file exceeded maximum!!! "); Request.getrequestdispatcher ("/message.jsp "). Forward (request,response); return;} catch (Fileuploadbase.sizelimitexceededexception e) {e.printstacktrace (); Request.setattribute ("Message", " The total size of the uploaded file exceeds the maximum limit!!! "); Request.getrequestdispatcher ("/message.jsp "). Forward (request,response); return;} catch (Exception e) {message = "File upload failed!" "; E.printstacktrace ();} Request.setattribute ("message", message); Request.getrequestdispatcher ("/message.jsp"). Forward (request, response) ;} private string Makefilename (string filename) {///2.jpg//to prevent file coverage from occurring, to generate a unique file name for the upload file int index = Filename.lastindexof ( "."); String fileaname = filename.substring (0,index) + "_" + Uuid.randomuuid (). toString () + filename.substring (index); return F Ileaname;}}


3 Add foreground results display file message.jsp
<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >





4 Display file List 4.1 Add servlet processing file Listfileservlet.java,url access path to/listfileservlet. Loops through the files that traverse the Web-info\upload folder.
Package Cjr.servlet;import Java.io.file;import java.io.ioexception;import java.util.hashmap;import java.util.Map; Import Javax.servlet.servletexception;import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;public class ListFileServlet Extends HttpServlet {public void doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doPost (request, response);} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// Gets the directory where the file was uploaded String Uploadfilepath = This.getservletcontext (). Getrealpath ("/web-inf/upload");//Store the file name to download map<string , string> filenamemap = new hashmap<string, string> ();//recursively traverse all files and directories in the FilePath directory, storing the file name in the Map collection listfile ( New file (Uploadfilepath), filenamemap);//file can either represent a file or represent a directory//send a map collection to a listfile.jsp page for display Request.setattribute ("fileNameMap", fileNameMap); Request.getrequestdispatcher ("/LISTFILE.JSP "). Forward (request, response);} public void listfile (file file, map<string, string> Map) {//If file is not a document, but a directory if (!file.isfile ()) {//lists the directory under which the Files and directories file[] files = file.listfiles ();//traversal files[] Array for (file F:Files) {//recursive listfile (f, map);}} else {String fileorgname = File.getname (); int index1 = Fileorgname.lastindexof ("_"); int index2 = Fileorgname.lastindexof ("."); String fileName = fileorgname.substring (0, index1) + fileorgname.substring (INDEX2); Map.put (File.getname (), fileName);}}}

4.2 Adding a display interface listfile.jsp
<%@ page Language= "java" import= "java.util.*" pageencoding= "UTF-8"%><%@ taglib prefix= "C" uri= "http://java.sun.com/jsp /jstl/core "%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

5 File Download Add File Downloadservlet.java, set access Access Url:/downloadservlet
Package Cjr.servlet;import Java.io.file;import Java.io.fileinputstream;import java.io.ioexception;import Java.io.outputstream;import Java.io.printwriter;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 response) throws Servletexception, IOException {doPost (Request, Response);} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {// Get the filename to download string filename = request.getparameter ("filename"); 23239283-92489-Avatar. Avifilename = new String (filename.getbytes ("iso8859-1"), "UTF-8");//uploaded files are saved in/web-inf/ The upload directory is a subdirectory of string filesaverootpath = This.getservletcontext (). Getrealpath ("/web-inf/upload");//Get file to download File = new File (Filesaverootpath + "\ \" + fileName);//If files do not existif (!file.exists ()) {Request.setattribute ("message", "The resource you want to download has been deleted!! "); Request.getrequestdispatcher ("/message.jsp "). Forward (request,response); return;} Processing file name int index1 = Filename.lastindexof ("_"); int index2 = Filename.lastindexof ("."); String realname = filename.substring (0, index1) + filename.substring (INDEX2);//Set the response header, 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 file input stream FileInputStream in = new FileInputStream (filesaverootpath + "\ \" + fileName)//Create output stream outputstream out = response.g Etoutputstream ();//create buffer byte buffer[] = new Byte[1024];int len = 0;//Loop reads the contents of the input stream into the buffer while (len = in.read (buffer)) &G T 0) {//output buffer contents to browser, implement file download out.write (buffer, 0, Len);} Close file input stream in.close ();//Close output stream out.close ();}}







reference:http://www.jb51.net/article/70543.htm


Java File upload 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.