在我們Web應(yīng)用系統(tǒng)開發(fā)當中,文件的上傳和下載的功能是非常常用的功能。本文將為各位小伙伴講解一下JavaWeb實現(xiàn)上傳和下載文件功能的實例,詳細內(nèi)容如下。
第一步:導包
導入commons-fileupload-1.3.3.jar和commons-io-2.4.jar兩個依賴包
第二步:編寫前端頁面
1、提交頁面 index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath }/fileUpload" method="post" enctype="multipart/form-data">
頭像:<input type="file" name="img" accept="image/*"/>
<input type="submit" value="提交"/>
</form>
</body>
</html>
2、結(jié)果頁面 result.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<center>
<a href="${pageContext.request.contextPath }/download?filename=${filename}" >
<img alt="xx" src="https://atts.w3cschool.cn/attachments/${src }">
</a>
</center>
</body>
</html>
第三步:編寫上傳和下載代碼
1、上傳圖片 fileUpload.java
package cn.yz123123.controller;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
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("/fileUpload")
@MultipartConfig
public class fileUpload extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//String username = request.getParameter("username");
Part part = request.getPart("img");
//獲取文件的真實名稱
String header = part.getHeader("content-disposition");
String realName = header.substring(header.indexOf("filename=")+10, header.length()-1);
//獲取文件自身流
InputStream inputStream = part.getInputStream();
//獲取file真實路徑,如果沒有則創(chuàng)建
String dir = request.getServletContext().getRealPath("/file/");
File dirFile = new File(dir);
//上面只是實例化了一個對象,并沒有真正的創(chuàng)建一個文件夾
if (!dirFile.exists()) {
dirFile.mkdirs();
}
//創(chuàng)建文件對象,并用流的形式寫在相應(yīng)的文件夾中
File file = new File(dir, realName);
FileOutputStream fileOutputStream = new FileOutputStream(file);
byte[] buf = new byte[1024];
int len;
while((len=inputStream.read(buf))!=-1) {
fileOutputStream.write(buf, 0, len);
}
fileOutputStream.close();
inputStream.close();
//以下為測試
request.setAttribute("src", request.getContextPath()+"/file/"+realName);
request.setAttribute("filename", realName);
request.getRequestDispatcher("/result.jsp").forward(request, response);
}
}
2、下載圖片 fileDownload.java
package cn.yz123123.controller;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(urlPatterns = "/download")
public class fileDownload extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String filename = req.getParameter("filename");
//獲取文件的真實路徑
String filePath = req.getServletContext().getRealPath("/file/"+filename);
FileInputStream fileInputStream = new FileInputStream(filePath);
resp.setCharacterEncoding("UTF-8");
resp.setHeader("Content-Disposition","attachment;filename="+UUID.randomUUID()+filename);
ServletOutputStream outputStream = resp.getOutputStream();
byte[] buf = new byte[1024];
int len;
while((len=fileInputStream.read(buf))!=-1) {
outputStream.write(buf, 0, len);
}
outputStream.close();
fileInputStream.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
}
}
以上就是關(guān)于JavaWeb實現(xiàn)上傳和下載文件功能實例的全部內(nèi)容,想要了解更多關(guān)于JavaWeb開發(fā)的詳細內(nèi)容,請關(guān)注W3Cschool,也希望大家多多支持。