servlet實現文件上傳下載的最簡單示例

文件下載

以PDF文件爲例,文件在src下:java

package course.servlet;

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

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


@WebServlet("/DownloadServlet")
public class DownloadServlet extends HttpServlet{

/**
 * 下載PDF文件
 */
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	//聲明文檔類型
	resp.setContentType("application/pdf");
	//一、讀取服務器上的PDF文件
    InputStream in = DownloadServlet.class.getClassLoader().getResourceAsStream("/draw.pdf");
	//二、讀取的同時 寫入outputstream
	OutputStream out = resp.getOutputStream();
	writeByte(in, out);
}

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	System.out.println("跳轉到了doGET");
	doPost(req, resp);
}

/**
 * 讀取文件並輸出
 */
public void writeByte(InputStream in, OutputStream out) throws IOException {
	int count = 0;
	byte[] b = new byte[1024];
	while ((count=in.read(b))!=-1) {
		out.write(b);
	}
	System.out.println("輸入成功");
	
	in.close();
	out.close();
}

}

文件上傳

以PDF文件爲例,上傳路徑爲絕對路徑:服務器

package course.servlet;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

@WebServlet("/UploadServlet")
@MultipartConfig
public class UploadServlet extends HttpServlet{

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	super.doGet(req, resp);
}

protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	Part part = req.getPart("uploadPDF");
	String fileName = getFileName(part);
	writeByte(part, fileName);
}

private String getFileName(Part part) {
	String header = part.getHeader("Content-Disposition");
	String result = header.substring(header.indexOf("filename=\"") + 10, header.lastIndexOf("\""));
	return result;
}

private void writeByte(Part part, String fileName) throws IOException {
	InputStream inputStream = part.getInputStream();
	OutputStream outputStream = new FileOutputStream("D:\\WorkSpaces\\eclipse-workspace\\MyFirstWebProject\\WebContent\\WEB-INF\\" + fileName);
	writeByte(inputStream, outputStream);
}

private void writeByte(InputStream inputStream, OutputStream outputStream) throws IOException {
	byte[] b = new byte[1024];
	int count = 0;
	while((count=inputStream.read(b))!=-1) {
		outputStream.write(b);
	}
	inputStream.close();
	outputStream.close();
}
}
相關文章
相關標籤/搜索