1.上传
(1)基于Ajax提交
前端
<body>
<div class="content">
<input type="file" id="file" name="file">
<button onclick="upload()">提交</button>
</div>
</body>
<script>
function upload() {
let fileObj =document.getElementById("file").files[0];
if (typeof(fileObj)=='undefined'||fileObj==null){
alert("请选择文件上传");
return;
}
let formFile=new FormData();//实例化一个表单对象
formFile.append("file",fileObj);//给表单对象添加参数,这里添加的是文件对象,相当于name属性
$.ajax({
type:"post",
url:"http://localhost:8080/servlet_demo08_war_exploded/upload",
data:formFile,//提交表单
cache:false,//上传文件不用缓存
processData:false,//用于对data参数进行序列化处理 这里必须false
contentType:false,
success: function(res) {
alert(res)
}
})
}
</script>
后端
@WebServlet("/upload")
@MultipartConfig //上传文件的控制器必须加@MultipartConfig
public class UpLoadFile extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
Part file = req.getPart("file"); //使用part接口来获取前端传过来的文件对象,part接口只有在类上注明了@MultipartConfig才有效
resp.setContentType("text/html;charset=utf8");
if (file!=null&&file.getSize()!=0){
String filename=file.getSubmittedFileName();
file.write("E://idea/servlet-demo08/upLoadFiles/"+ UUID.randomUUID().toString()+filename.substring(filename.lastIndexOf(".")));//文件写入位置路径,这里需要写绝对路径,且为了保证上传文件名不重复这里采用了UUID得到唯一码
resp.getWriter().write("上传成功!");
}
}
}
(2)基于表单提交
前端
注意:表单上传文件必须加参数enctype="multipart/form-data",否则上传失效
<form action="upload" enctype="multipart/form-data" method="post">
选择文件<input type="file" name="file"/>
<input type="submit" name="upload" value="上传"/>
</form>
后端
@WebServlet("/upload")
@MultipartConfig //上传文件的控制器必须加@MultipartConfig
public class UpLoadFile extends HttpServlet {
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
Part file = req.getPart("file"); //使用part接口来获取前端传过来的文件对象,part接口只有在类上注明了@MultipartConfig才有效
resp.setContentType("text/html;charset=utf8");
if (file!=null&&file.getSize()!=0){
String filename=file.getSubmittedFileName();
file.write("E://idea/servlet-demo08/upLoadFiles/"+ UUID.randomUUID().toString()+filename.substring(filename.lastIndexOf(".")));//文件写入位置路径,这里需要写绝对路径,且为了保证上传文件名不重复这里采用了UUID得到唯一码
resp.getWriter().write("上传成功!");
}
}
}
2.文件下载
(1)在tomcat管辖范围
@WebServlet("/down")
public class DownLoad extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("application/x-msdownload");//文件下载时必须设置响应头如上
String fileName="我的文件.txt";//文件下载时允许有中文
resp.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));//当文件有中文是需要设置编码
ServletOutputStream outputStream = resp.getOutputStream();//获取输出流
FileInputStream fileInputStream = new FileInputStream("C:\\Users\\Administrator\\Desktop\\chen.txt");//获取文件输入流
int i;
byte[] bytes=new byte[1024];//建立byte数组每次读取1kb
while ((i=fileInputStream.read())!=-1){
outputStream.write(bytes,0,i);
}
outputStream.close();
fileInputStream.close();//关闭流
}
}
(2)若不在tomcat管辖范围则可以使用<a>标签下载
<img src="img/wujita.jpeg" style="width: 200px;height: 200px" id="myfile">
<a href="img/wujita.jpeg" download="<%= UUID.randomUUID().toString()+".jpeg" %>">下载</a>
a便签中的href表示的是获取文件路径,download是下载时的文件名称。