File Upload and download

Source: Internet
Author: User

For file upload, the browser in the process of uploading the file as a stream to the server side, if directly using the servlet to get the input stream of the uploaded file and then parse the request parameters inside is more trouble, So the general choice is to use the Apache Open Source Tool common-fileupload This file upload component. Common-fileupload is dependent on Common-io for this package, so you need to download this package as well.

File Upload process:

1. JSP page upload file

2, the background to get the file stream (the principle is the same, the implementation of different ways.)

Sevelet is generally obtained from httpservletrequest by Servletfileupload;

The struts2 automatically encapsulates the file stream as a document object; SPRINGMVC is Multipartfile)

3. Get output stream, generate file in corresponding directory

File upload page index.jsp code
1<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "2   3pageencoding= "UTF-8"%>4     5<%@ taglib prefix= "C" uri= "Http://java.sun.com/jsp/jstl/core"%>6   7    8   9<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" >Ten    One A    - -    the<meta http-equiv= "Content-type" content= "text/html; Charset=utf-8 "> -    -<title>insert title here</title> -    + -    +<body> A      at -    -<form action= "FileUpload" method= "post" enctype= "Multipart/form-data" > -    -<input type= "hidden" name= "method" value= "Upload"/> -    in<input type= "File" name= "file"/> -    to<input type= "Submit" value= "Upload"/> +    -</form> the  *</body> $   Panax Notoginseng
View Code

File Processing Class Code

1  PackageCom.updown.controller;2 3 ImportJava.io.BufferedInputStream;4 ImportJava.io.BufferedOutputStream;5 ImportJava.io.File;6 ImportJava.io.FileInputStream;7 ImportJava.io.InputStream;8 ImportJava.io.OutputStream;9 ImportJava.text.SimpleDateFormat;Ten Importjava.util.Date; One Importjava.util.List; A ImportJava.util.UUID; -  - ImportJavax.annotation.Resource; the Importjavax.servlet.http.HttpServletRequest; - ImportJavax.servlet.http.HttpServletResponse; - ImportOrg.springframework.stereotype.Controller; - Importorg.springframework.web.bind.annotation.RequestMapping; + ImportOrg.springframework.web.multipart.MultipartFile; - Importorg.springframework.web.multipart.MultipartHttpServletRequest; +  A Importcom.updown.entity.Content; at ImportCom.updown.service.ContentService; -  - @Controller -  Public classfileoperatecontroller{ -        -     /**  in * Upload Files -      * @paramRequest to      * @paramModel +      * @return  -      */  the@Resource (name = "Contentservice") *      PrivateContentservice Contentservice; $ @RequestMappingPanax Notoginseng      PublicString toupload () { -         return"Index";  the     }  +      A@RequestMapping (value= "FileUpload") the      PublicString upload (httpservletrequest request)throwsexception{ +          -Multiparthttpservletrequest multipartrequest =(multiparthttpservletrequest) request;  $SimpleDateFormat DateFormat =NewSimpleDateFormat ("Yyyy/mm/dd/hh");  $         //building a saved directory -String Filerelativepath = "/files" + Dateformat.format (NewDate ());  -         //get the true path to the saved directory theString Filerealpath =request.getsession (). Getservletcontext (). Getrealpath (Filerelativepath);  -         //Create a directory based on a real pathWuyiFile SaveFile =NewFile (Filerealpath);  the         if(!savefile.exists ()) -Savefile.mkdirs ();//mkdirs () returns when and only if the directory is created, and all required parent directories Wu         //The page control's file stream, which returns the contents of the uploaded file in this request plus a description, or if it does not exist, returns an empty -Multipartfile multipartfile = multipartrequest.getfile ("File");  About         //gets the suffix of the file, Getoriginalfilename returns the file system to the original filename on the client $String suffix =multipartfile.getoriginalfilename (). Substring -(Multipartfile.getoriginalfilename (). LastIndexOf ("."));  -         //white list of files -String[] filetype={"gif", "JPG", "JPEG", "PNG", "BMP", "Doc", "Docx", "PDF", "xls", "xlsx", "txt", "zip", "rar"}; A         //loops through each string in the string array to see if all of the found contents are included +          for(inti=0;i<filetype.length;i++){ the                if(Filetype[i].indexof (suffix.substring (1))!=-1){ -          $String uuid =Uuid.randomuuid (). toString (); theString FileName =Multipartfile.getoriginalfilename ();  the         //spell complete file save path Plus file theString Fileabsolutepath = Filerealpath + File.separator +FileName;  theFile File =NewFile (fileabsolutepath); -          in Multipartfile.transferto (file);  the       theContent content=NewContent (); About Content.setpath (filerelativepath); theContent.setdate (Dateformat.format (NewDate ()) +uuid); the Content.settitle (fileName); the         //Database Operations +         intup_result=contentservice.addcontent (content); -List<content> list=contentservice.listalldepartment (); theRequest.setattribute ("list", list);Bayi         }       the                } the         return"/success"; -     } -      the     /**  the * Download File the      * @paramRequest the      * @paramResponse -      * @return  the      */  the@RequestMapping (value = "Download")   the      Public voidDownload (httpservletrequest request,httpservletresponse response)throwsexception{94  theString Title=request.getparameter ("title"); theContent content=Contentservice.getcontentbytitle (title); theString Filesqlsavepath =Content.getpath ();98String fileserverpath=request.getsession (). Getservletcontext (). Getrealpath (Filesqlsavepath); AboutString fileabsolutepath=fileserverpath+ "\ \" +title; -File File =NewFile (fileabsolutepath);101         //get the suffix name of the file102String suffix = title.substring (Title.lastindexof (".")));103         //download the file as a stream104InputStream FIS =NewBufferedinputstream (NewFileInputStream (Fileabsolutepath)); the         //public int available () throws ioexception{} returns the number of bytes that the next method that is called on this input stream can be read from this input stream in a nonblocking manner. Returns an integer value106         byte[] buffer =New byte[Fis.available ()];107         //This method reads bytes of buffer.length length from the input stream. Returns the number of bytes read. Returns 1 if it is the end of the file108 fis.read (buffer);109 fis.close (); the         //Empty Response111 Response.reset (); the         //set the header of the response113Response.AddHeader ("Content-disposition", "attachment;filename=" +NewString (Title.getbytes ("gb2312"), "Iso8859-1")); theResponse.AddHeader ("Content-length", "" "+file.length ()); theOutputStream toclient =NewBufferedoutputstream (Response.getoutputstream ()); theResponse.setcontenttype ("Application/octet-stream");117 toclient.write (buffer);118 Toclient.flush ();119 toclient.close (); -     }121}
View Code

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.