File Download-springmvc Test

Source: Internet
Author: User

Directly modify the file path can be, others do not need to modify, Help class has been written for everyone, can be used directly

1, Scroller:

/** * Download File * @author Liupeng * @param request * @param response * @return * @throws Exception * * @RequestMapping (value= "/te Stfiledown ") Public String Testfiledown (httpservletrequest request,httpservletresponse response) throws exception{ Fileoperator.filedownload ("E:" +file.separator+ "tt.pdf", response); return null;}

2, Fileoperator:

Package Com.utcsoft.common.util;import Java.io.bufferedinputstream;import Java.io.bufferedwriter;import Java.io.file;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.FileOutputStream; Import Java.io.filewriter;import java.io.ioexception;import Java.io.inputstream;import Java.io.OutputStream;import Java.io.printwriter;import Java.net.urlencoder;import Java.util.properties;import Java.util.zip.ZipEntry;import Java.util.zip.zipoutputstream;import Javax.servlet.servletconfig;import Javax.servlet.servletexception;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Org.apache.commons.logging.log;import Org.apache.commons.logging.logfactory;import Com.utcsoft.common.servlet.log4jinitservlet;public class Fileoperator {Private final static Log logger = Logfactory.getlog (fileoperator.class);p ublic static String path = "C:";p ublic static int count = 0;public Fileoperator () { String tmp = GetClass (). GetResource ("/"). GetpaTh (); SYSTEM.OUT.PRINTLN (TMP);} public static String Getrootpath () {try{string proname = Log4jinitservlet.propertiespath; String tmp = System.getproperty ("User.dir");p ath = tmp.substring (0, Tmp.lastindexof (file.separator) + 1) + "bid" + file.se Parator;/*string osname = System.getproperties (). GetProperty ("Os.name"); if (Osname.tolowercase (). IndexOf ("Windows" ) = =-1) {path = "/home/bid/";} */inputstream in = new Bufferedinputstream (new FileInputStream (Proname)); Properties P = new properties ();p. Load (in),//p.containskey ("Path.file") if (!p.getproperty ("Path.file"). ToString (). Trim (). Equals ("")) {path = P.getproperty ("Path.file");}} catch (Exception ex) {Logger.error ("[Fileoperator]-Get file storage Path exception-" + Ex.getmessage ());} return path;} Transfer file stream to server public static void FileUpload (String filePath, httpservletrequest request) throws Servletexception, Ioexception{outputstream out = Null;inputstream ins = null;try {ins = Request.getinputstream (), out = new FileOutputStream ( FilePath); byte[] FileData = new byte[1024]; int readcount = 0; count = 0;while ((Readcount=ins.read (filedata,0,1024))! =-1) {out.write (filedata,0,readcount); count + = Readcount;} Out.flush (); Logger.info ("[FileUpload]-Read file size:" +count + "=======" + request.getclass () + ":" + FilePath);} catch (Exception ex) {ex.printstacktrace (); Logger.error ("[FileUpload]-" + ex + "=======" + Request.getclass ());} finally {out.close (); Ins.close ();}}  Transfer file stream to server public static string loadString (string path) throws IOException {StringBuffer buf = new StringBuffer ();  String line = null;  Java.io.File File = new Java.io.File (path); Java.io.InputStream in = null;  Java.io.OutputStream out = null;  Java.io.BufferedReader reader = null;  try {//get FileInputStream stream;  in = new Java.io.FileInputStream (file);  Get BufferedReader stream;  reader = new Java.io.BufferedReader (new Java.io.InputStreamReader (in));   Iterates through the rows and exits the loop if the read behavior is null;  while (line = Reader.readline ())! = null) {Buf.append (line). append ("\ n"); } catch (FilenotfoundexcEption e) {e.printstacktrace ();  } catch (IOException ex) {ex.printstacktrace ();  } finally {reader.close ();  In.close ();  } return buf.tostring (); }//Online save and write file public static void ReadFile (String path1, String path2) throws IOException {outputstream out = new FILEOUTPU TStream (path2); try {//create a file stream object FileInputStream is = new FileInputStream (path1);//sets the number of bytes read int n = 512;byte buffer[] = new B Yte[n];int readcount = 0; count = 0;//reads the input stream while ((readcount=is.read (buffer, 0, n))! =-1) {Out.write (Buffer,0,readcount) ; count + = Readcount;} Out.flush ();//Close input stream out.close (); Is.close ();} catch (IOException IoE) {}}//transfer file stream to client public static void FileDownload (String filePath, httpservletresponse response) Throws Servletexception, Ioexception{if ("". Equals (FilePath)) Return;outputstream out = Null;inputstream ins = null;try { String fileName = Stringoperator.getfilename (FilePath); File File = new file (filePath); Long filelength = File.length (); ins = new FileInputStream (filePath); out = Response.geToutputstream (); byte[] FileData = new Byte[1024];int readcount = 0; count = 0;//response.setheader ("Content-type", "appli Cation/octet-stream "), Response.setcontenttype (" Application/octet-stream "); Response.setheader (" Content-disposition "," attachment; Filename= "+urlencoder.encode (FileName," UTF-8 ")); Response.setheader (" Content-length ", string.valueof (Filelength) ); while ((Readcount=ins.read (filedata,0,1024))! =-1) {out.write (filedata,0,readcount); count + = Readcount;} Out.flush (); Response.flushbuffer (); Logger.info ("[FileDownload]-Write file size:" +count + "=======" + Response.getclass () + ":" + FilePath);} catch (Exception ex) {ex.printstacktrace (); Logger.error ("[FileDownload]-" + ex+ "=======" + Response.getclass ());} finally {out.close (); Ins.close ();} PrintWriter out1 = Response.getwriter ();//out.clear ();//out = Pagecontext.pushbody ();} File upload--Test passed public static Boolean Fileuploadex (String FilePath, String fileName, Long fileSize, InputStream InputStream) {Boolean flag = False;try{//filepath = Stringoperator.getencodestring (filePath);//filename = stringoperator.getencodestring (fileName); Logger.info ("[ Fileuploadex]-filepath= "+filepath+" filename= "+filename"; inputstream in = InputStream; File filed = new file (FilePath), if (!filed.exists ()) {filed.mkdirs ();} byte[] buffer = new byte[4096]; File OutFile = new file (FilePath + file.separator + fileName); FileOutputStream BOS = Null;bos = new Java.io.FileOutputStream (outFile); int Read;long YX = 0;while (read = in.read (buffer )! =-1) {YX = yx + read;bos.write (buffer, 0, read);} In.close (); Bos.flush (); Bos.close (); Logger.info ("[Fileuploadex]-File size:{" + FileSize + "}, read:{" + Yx + "}"); flag = true;} catch (Exception ex) {logger.error (ex);} return flag;}    public static void WriteFile (String filepath) {File File = new file (path); The file to be written bufferedwriter writer = null;try {if (!file.exists ()) File.createnewfile (); writer = new BufferedWriter (new FileWriter (file)); Writer.write ("111111111111111111111");} catch (IOException e) {e.printstAcktrace ();} finally {if (writer! = null) try {writer.close ();} catch (IOException e) {e.printstacktrace ();}}}  /** * Deletes the specified directory or file according to the path, regardless of whether it exists or not * @param spath the directory or file to be deleted * @return Delete succeeds returns True, otherwise false.  */public static Boolean DeleteFolder (String spath) {Boolean flag = false;  File File = new file (spath);  Determine if the directory or file exists if (!file.exists ()) {//does not exist returns false return flag;  } else {return deletedirectory (spath); }}/** * Delete a single file * @param spath The file name of the deleted files * @return A single file delete succeeds returns TRUE, otherwise false */public static Boolean DeleteFile (String spath)  {Boolean flag = false;  File File = new file (spath);  If the path is a file and is not empty, delete if (File.isfile () && file.exists ()) {file.delete ();  Flag = true;  } return flag; }/** * Delete directories (folders) and files under directory * @param spath The file path of the deleted directory * @return Directory Delete succeeded return true, otherwise false */public static Boolean de Letedirectory (String spath) {//If spath does not end with a file delimiter, automatically adds the file delimiter if (!spath.endswith (File.separator)) {spath = spath + file.se  Parator; } File Dirfile =New File (spath);  If the dir corresponding file does not exist, or is not a directory, exit if (!dirfile.exists () | | |!dirfile.isdirectory ()) {return false;  } Boolean flag = true;  Delete all files (including subdirectories) under folder file[] files = dirfile.listfiles (); for (int i = 0; i < files.length; i++) {//delete sub-file if (Files[i].isfile ()) {flag = DeleteFile (files[i].getabsolutepath  ());  if (!flag) break;  }//Delete sub-directory else {flag = DeleteDirectory (Files[i].getabsolutepath ());  if (!flag) break;  }} if (!flag) return false;  Delete current directory if (Dirfile.delete ()) {return true;  } else {return false;  }} public static void Main (string[] args) {path = "f:\\test";  Boolean result = Fileoperator.deletefolder (path);  SYSTEM.OUT.PRINTLN (result); }//You can first generate a zip file for all selected files and then download the zip file to enable bulk download of public static void Zipoutputstreamdemo (String zipspath,string SourceFile) throws Exception {byte[] buffer = new byte[1024];//The generated zip file is named demo.zipstring strzipname = "C:demo.zip"; Zipoutputstream out = new Zipoutputstream (new FileOutputStream (Strzipname));//Two files that need to be downloaded simultaneously result.txt, source.txtfile[] file1 = {new File ("C:\\test.pdf"), New file ("C:\\test11.pdf")};for (int i=0;i <file1.length;i++) {FileInputStream FIS = new FileInputStream (File1[i]); Out.putnextentry (new ZipEntry (File1[i]. GetName ())); int len;//reads the contents of the file to be downloaded, packages it into a zip file while ((len = fis.read (buffer)) >0) {out.write (Buffer,0,len);} Out.closeentry (); Fis.close ();} Out.close (); System.out.println ("Generate Demo.zip Success");}}


File Download-springmvc Test

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.