File Download-SpringMVC test, File Download-springmvc

Source: Internet
Author: User
Tags file separator

File Download-SpringMVC test, File Download-springmvc

You can directly modify the file path, and do not need to modify other files. The help class has been written for you and can be used directly.

1. Scroller:

/*** Download file ** @ author liupeng * @ param request * @ param response * @ return * @ throws Exception */@ RequestMapping (value = "/testFileDown ") public String testFileDown (HttpServletRequest request, HttpServletResponse response) throws Exception {FileOperator. fileDownload ("e:" + File. separator + "ttator", 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. prope Rties; 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 {pr Ivate final static Log logger = LogFactory. getLog (FileOperator. class); public static String path = "c:"; public 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 "); path = tmp. substring (0, tmp. lastIndexOf (File. separator) + 1) + "bid" + File. separator;/* 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]-An error occurred while obtaining the file storage path-" + ex. getMessage ();} return path;} // transfer the file to the server public static void FileUpload (String filePath, HttpServletRequest request) throws ServletException, IOException {OutputStream out = null; inputStream ins = null; try {ins = request. getInputStream (); ou T = new FileOutputStream (filePath); byte [] fileData = new byte [1024]; int readCount = 0; count = 0; while (readCount = ins. read (fileData ))! =-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 the file to the server public static String loadString (String path) throws IOException {Str IngBuffer 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 the fileInputStream stream; in = new java. io. fileInputStream (file); // gets the bufferedReader stream; reader = new java. io. bufferedReader (new java. io. inputStreamReader (in); // read rows cyclically. If the read behavior is null, the loop is exited. 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 () ;}// save and write the public static void ReadFile (String path1, String path2) throws IOException {OutputStream out = new FileOutputStream (path2 ); try {// create a file stream object FileInputStream is = new FileInputStre Am (path1); // you can specify the number of bytes to read. int n = 512; byte buffer [] = new byte [n]; int readCount = 0; count = 0; // read the input stream while (readCount = is. read (buffer, 0, n ))! =-1) {out. write (buffer, 0, readCount); count + = readCount;} out. flush (); // close the input stream out. close (); is. close () ;}catch (IOException ioe) {}// transfer the file to the 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 fil E = 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", "application/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 ))! =-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 the 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 file D = 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. writes ("111111111111111111111");} catch (IOException e) {e. printStackTrace ();} finally {if (writer! = Null) try {writer. close ();} catch (IOException e) {e. printStackTrace () ;}}/ *** deletes a specified directory or file based on the path, whether it exists or not * @ param sPath indicates the directory or file to be deleted * @ return returns true if the deletion is successful. Otherwise, false is returned. */Public static boolean DeleteFolder (String sPath) {boolean flag = false; File file = new File (sPath); // determine whether a directory or File exists if (! File. exists () {// returns false return flag;} else {return deleteDirectory (sPath );}} /*** delete a single file * @ param sPath File Name of the deleted file * @ return true if the deletion of a single file is successful; otherwise, false */public static boolean deleteFile (String sPath) is returned) {boolean flag = false; File file = new File (sPath); // Delete if (file. isFile () & file. exists () {file. delete (); flag = true;} return flag;}/*** delete the directory (folder) and files under the directory * @ param sPa Th returns true if the directory to be deleted is successfully deleted * @ return. Otherwise, false */public static boolean deleteDirectory (String sPath) is returned. {// If sPath does not end with a file separator, automatically add the file separator if (! SPath. endsWith (File. separator) {sPath = sPath + File. separator;} File dirFile = new File (sPath); // exit if (! DirFile. exists () |! DirFile. isDirectory () {return false;} boolean flag = true; // delete all files in the folder (including subdirectories) File [] files = dirFile. listFiles (); for (int I = 0; I <files. length; I ++) {// Delete the sub-file if (files [I]. isFile () {flag = deleteFile (files [I]. getAbsolutePath (); if (! Flag) break;} // Delete the subdirectory else {flag = deleteDirectory (files [I]. getAbsolutePath (); if (! Flag) break;} if (! Flag) return false; // Delete the 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 generate a zip file for all selected files before downloading the file, you can download public static void ZipOutputStreamDemo (String zipsPath, String sourcefile) throws Exception {byte [] buffer = new byte [1024] in batches. // The generated ZIP file is named demo.zip String strZipName = "C: demo.zip "; ZipOutputStream out = new ZipOutputStream (new FileOutputStream (strZipName); // download two files at the same time: result.txt, source.txt File [] file1 = {new File (" C: \ test.pdf "), new File ("C :\\ test11.pdf")}; for (int I = 0; I <file1.length; I ++) {FileInputStream FCM = new FileInputStream (file1 [I]); out. putNextEntry (new ZipEntry (file1 [I]. getName (); int len; // read the content of the file to be downloaded and package it into the zip file while (len = Fi. read (buffer)> 0) {out. write (buffer, 0, len);} out. closeEntry (); FCM. close ();} out. close (); System. out. println ("demo.zip created ");}}



SpringMVC implements how the client receives the downloaded file

Blog.csdn.net/geloin/article/details/7537425

I just tried to download it.

How to master springMVC framework

The main content of spring is: ioc aop Transaction Management remote calls are the first three. If you get familiar with a small project, you will basically use it. The original intention of spring design is to facilitate development and design. Another aspect of spring design is that it is not intrusive to the system. It is easier to get started with spring, but it takes some time to be proficient. We recommend that you read the spring in action book.

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.