檔案下載-SpringMVC中測試,檔案下載-springmvc

來源:互聯網
上載者:User

檔案下載-SpringMVC中測試,檔案下載-springmvc

直接修改檔案路徑就可以,其他都不需要修改,協助類已經為大家寫好,可直接使用

1、Scroller:

/** * 下載檔案 * @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+"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);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] - 擷取檔案存放路徑出現異常 - " + ex.getMessage());}return path;}//傳送檔案流到服務端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();}}//傳送檔案流到服務端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  {  //擷取fileInputStream流;  in = new java.io.FileInputStream(file);  //擷取bufferedReader流;  reader = new java.io.BufferedReader(new java.io.InputStreamReader(  in));  //迴圈讀取行,如果讀取的行為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();  }  //線上儲存並寫檔案public static void ReadFile(String path1, String path2) throws IOException  {OutputStream out = new FileOutputStream(path2);try {// 建立檔案流對象FileInputStream is = new FileInputStream(path1);// 設定讀取的位元組數int n = 512;byte buffer[] = new byte[n];int readCount = 0 ;count = 0;// 讀取輸入資料流while ((readCount=is.read(buffer, 0, n) )!= -1) {out.write(buffer,0,readCount);count += readCount;}out.flush();// 關閉輸入資料流out.close();is.close();} catch (IOException ioe) {} }//傳送檔案流到用戶端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", "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,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();}//檔案上傳--測試通過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);    //要寫入的檔案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();}}}/**  *  根據路徑刪除指定的目錄或檔案,無論存在與否  *@param sPath  要刪除的目錄或檔案  *@return 刪除成功返回 true,否則返回 false。  */  public static boolean DeleteFolder(String sPath) {boolean  flag = false;  File  file = new File(sPath);  // 判斷目錄或檔案是否存在  if (!file.exists()) {  // 不存在返回 false  return flag;  } else {  return deleteDirectory(sPath);  }  }/**  * 刪除單個檔案  * @param   sPath    被刪除檔案的檔案名稱  * @return 單個檔案刪除成功返回true,否則返回false  */  public static boolean deleteFile(String sPath) { boolean   flag = false;  File  file = new File(sPath);  // 路徑為檔案且不為空白則進行刪除  if (file.isFile() && file.exists()) {  file.delete();  flag = true;  }  return flag;  }  /**  * 刪除目錄(檔案夾)以及目錄下的檔案  * @param   sPath 被刪除目錄的檔案路徑  * @return  目錄刪除成功返回true,否則返回false  */  public  static boolean deleteDirectory(String sPath) {//如果sPath不以檔案分隔字元結尾,自動添加檔案分隔字元  if (!sPath.endsWith(File.separator)) {  sPath = sPath + File.separator;  }  File dirFile = new File(sPath);  //如果dir對應的檔案不存在,或者不是一個目錄,則退出  if (!dirFile.exists() || !dirFile.isDirectory()) {return false;  }  boolean flag = true;  //刪除檔案夾下的所有檔案(包括子目錄)  File[] files = dirFile.listFiles();  for (int i = 0; i < files.length; i++) {  //刪除子檔案  if (files[i].isFile()) {  flag = deleteFile(files[i].getAbsolutePath());  if (!flag) break;  } //刪除子目錄  else {  flag = deleteDirectory(files[i].getAbsolutePath());  if (!flag) break;  }  }  if (!flag) return false;  //刪除目前的目錄  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);  } //可以先將選擇的所有的檔案產生一個zip檔案,然後再下載,該zip檔案,即可實現批量下載public  static void  ZipOutputStreamDemo(String zipsPath,String sourcefile) throws Exception  {byte[] buffer = new byte[1024];//產生的ZIP檔案名稱為Demo.zipString strZipName = "C:Demo.zip";ZipOutputStream out = new ZipOutputStream(new FileOutputStream(strZipName));//需要同時下載的兩個檔案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;//讀入需要下載的檔案的內容,打包到zip檔案while((len = fis.read(buffer))>0) {out.write(buffer,0,len);}out.closeEntry();fis.close();}out.close();System.out.println("產生Demo.zip成功");}}



springMVC實現檔案下載時用戶端怎接收下載的檔案

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

我剛試了下載是可以的。
 
怎掌握springMVC架構

spring主要內容是:IOC AOP 交易管理 遠程調用 最主要的是前面三個。 你弄個小項目熟悉下就基本會用了。 spring設計的初衷就是為了方便開發設計,他得另一個有點就是對系統是非侵入式起作用。 spring上手是比較容易的,但要精通那就需要好好花點時間了。 建議看看spring in action這本書
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.