1:上传功能
上传文件注意:
1:前台表单需要设置 enctype=“multipart/form-data”
2: 后台servlet需要在类上添加注解@MultipartConfig
1.1:编写前台页面【JSP】选择需要上传的文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>上传</title>
</head>
<body>
<form enctype="multipart/form-data" method="post" action="../upload">
选择文件:<input name="myFile" type="file" value="选择文件">
<br>
<input type="submit" value="上传文件">
</form>
</body>
</html>
1.2:后台接受文件,上传制定路径
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;
import java.io.IOException;
/**
* 上传内容
*/
@WebServlet("/upload")
@MultipartConfig
public class Uoload extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//根据name属性获取文件
Part myFile1 = req.getPart("myFile");
//获取上传文件的文件名
String submittedFileName = myFile1.getSubmittedFileName();
//获取当前项目在tomcat路径,作为指定的上传路径
String realPath = req.getServletContext().getRealPath("/");
//调用文件自己的写出方法
System.out.println(realPath+submittedFileName);
myFile1.write(realPath+submittedFileName);
}
}
2:下载功能
2.1:编写前台页面【JSP】
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>下载</title>
</head>
<body>
<form method="post" action="../download">
<input type="submit" name="fileUrl" value="D:\AAA_dowload\aDrive.exe">
</form>
</body>
</html>
2.2:编写后端Servlet接口
/**
* 下载文件
*/
@WebServlet("/download")
public class DownLoad extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//获取需要下载的文件,文件路径
String fileUrl = req.getParameter("fileUrl");
System.out.println(fileUrl);
//实例化文件
File file = new File(fileUrl);
// 判断文件是否存在,并且是一个文件
if(file.exists()&&file.isFile()) {
// 开始创建输出流开始下载,下载的时候,需要设置响应内容(浏览器无法使用某种方式或激活某个程序来处理的类型)
resp.setContentType("application/x-msdownload");
// 设置响应头信息
resp.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
FileInputStream fileInputStream = new FileInputStream(file);
ServletOutputStream outputStream = resp.getOutputStream();
byte[] bytes = new byte[1024];
int leng=0;
while ((leng=fileInputStream.read(bytes))!=-1){
outputStream.write(bytes,0,leng);
}
outputStream.flush();
outputStream.close();
fileInputStream.close();
}else {
resp.getWriter().write("文件不存在");
System.out.println("文件不存在");
}
}
}