在java Web中實現文件的上傳下載

1.首先前端利用表單收集用戶的個人信息,由於在網頁中顯示數據時以字符串顯示,在後臺的Servlet中獲取時,有內置的HttpServletRequest類,進行實例化後的request對象調用

getParameter()方法可獲取前端輸入的信息,可是當前臺中攜帶二進制文件時,此時的request對象將不能對二進制數據進行獲取,所以需要進行重新獲取。

具體操作爲:

(1)前端收集信息的表單的<from>標籤應添加entype屬性,其中取值爲multipart/form-data,(即給後臺顯示前臺傳輸的數據爲二進制數據)改屬性默認值是:application/x-www-form-urlencoded。(即給後臺顯示前臺傳輸的數據是普通的字符串數據)

(2)在前臺的<from>表單中添加<input type="file" name="filename">標籤,其中input標籤的type類型是file,代表文件。

(3)導入第三方的文件上傳下載的驅動包。

(4)進行後臺獲取值實現上傳和下載的功能;

2.具體如下:

(1)前端表單:

<body>
    <form action="uploadServlet" method="post" enctype="multipart/form-data">
    name:<input type="text" name="name"><br>
    age:<input type="text" name="age"><br>
    file:<input type="file" name="filename"><br>
    <input type="submit" value="submit">
    </form>
    
  </body>
(2)實現文件的上傳原理:

將文件保存到服務器的一個路徑;

在數據庫中記錄文件的路徑;

package com.file;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.List;

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.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class UploadServlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
			this.doPost(request, response);
		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html");
		DiskFileItemFactory factory=new DiskFileItemFactory();//文件上傳的緩衝模式(硬盤模式)
		ServletFileUpload upload=new ServletFileUpload(factory);//創建文件上傳的對象
		try {
			List<FileItem> l=upload.parseRequest(request);//將原來request中收集的普通域(可以作爲String文本數據)數據轉爲一個List泛型是FileItem(文件域:超文本數據)是中,其中調用parseRequest()方法
			String name="";
			String age="";
			String filename="";
			for(FileItem fi:l){//遍歷List集合
				if(fi.isFormField()){//獲取普通數據域的name屬性值
					filename=fi.getFieldName();
					if("name".equals(filename)){
						name=fi.getString();//獲取普通數據域的name屬性值對應的value值
					}else{
						age=fi.getString();
					}
				}else{//說明是文件域
					InputStream in=fi.getInputStream();//得到文件的輸入流
					String path=this.getServletContext().getRealPath("/files/"+fi.getName());//得到該應用程序的絕對路徑
					filename=fi.getName();
					System.out.println(path);
					OutputStream ou=new FileOutputStream(path);//對應得到路徑的輸出流
					byte [] b=new byte[100];//進行文件的複製操作
					int num=in.read(b);
					while(num!=-1){
						ou.write(b,0,num);
						num=in.read(b);
					}
					in.close();
					ou.close();
					filename="files/"+filename;
				}
				
			}
			request.setAttribute("name", name);
			request.setAttribute("age", age);
			request.setAttribute("filename", filename);
			request.getRequestDispatcher("show.jsp").forward(request, response);//進行請求轉發,跳轉至show.jsp界面顯示
	//response.sendRedirect("show.jsp");
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
(3)文件下載原理:

在瀏覽器中下載文件時:如果文件能夠被瀏覽器識別(圖片,文本等),瀏覽器會直接在線打開。而這裏實現的是瀏覽器不在線打開,點擊鼠標左鍵彈出保存的選項進行下載保存。

1.修改ContentType的屬性爲application/x-msdownload(告訴瀏覽器不要解析)默認是text\html(瀏覽器加載);

2.修改Content-Disposition屬性,該屬性設置瀏覽器對數據內容的展示方式,設置爲attachment(告訴瀏覽器不要在線打開),默認是inline(在線打開);

package com.file;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DownSrevlet extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		this.doPost(request, response);
		
	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		//response.setContentType("text/html");
		response.setContentType("application/x-msdownload");//瀏覽器不要解析
		
		
		String file=request.getParameter("filename");
		response.setHeader("Content-Disposition", "attachment;filename="+file);//設置不在線打開
		String path=this.getServletContext().getRealPath("/");
		InputStream in=new FileInputStream(path+file);//得到服務器上文件的輸入流
		System.out.println(path+file);
		OutputStream os=response.getOutputStream();//由響應得到對應此時客戶端的輸出流
		byte[] b=new byte[100];
		int num=in.read(b);//進行文件的複製
		while(num!=-1){
			os.write(b, 0, num);
			num=in.read(b);
			
		}
		in.close();
		os.close();
		
	}

運行的結果爲: 



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章