1, 文件的上传
准备jar包:commons-fileupload-1.2.2.jar commons-io-2.3.jar
Jsp中form标签的enctype=”multipart/form-data” 必须要加
upload.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/uploadSrevlet2" method="post" enctype="multipart/form-data">
上传文件介绍:<input type="text" name="fileContent" /> <br/>
上传文件 : <input type="file" name="fileTxt" /> <br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
Java代码:
package com.file.servlet;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.List;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
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;
@WebServlet(name = "uploadSrevlet2", urlPatterns = { "/uploadSrevlet2" })
public class UploadSrevlet2 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 {
try {
// 0 判断是否支持上传
if(! ServletFileUpload.isMultipartContent(request)){
throw new RuntimeException("请先填写enctype");
}
// 1 创建工厂
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
fileItemFactory.setSizeThreshold(1024 * 1024 * 2); //2M
fileItemFactory.setRepository(new File(this.getServletContext().getRealPath("/temp")));
// 2 创建核心类
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
// * 上传文件名的编码
servletFileUpload.setHeaderEncoding("UTF-8");
// 3 解析request获得上传的内容,获得所有的文件列表
List<FileItem> allFileItem = servletFileUpload.parseRequest(request);
// 4 遍历
for(FileItem fileItem : allFileItem){
// 5 上传字段 和 表单字段 -- type="file"称为上传字段,其他都是表单字段(普通字段)
if(fileItem.isFormField()){
// 6 普通字段
// 6.1 字段名称, <input name=""
String fieldName = fileItem.getFieldName();
System.out.println("字段名称 --> " + fieldName);
// 6.2 字段的内容
String fieldValue = fileItem.getString("UTF-8");
System.out.println("字段的内容 --> " + fieldValue);
} else {
// 7 上传字段
// 7.1 上传文件的名称
String fileName = fileItem.getName();
System.out.println("上传文件的名称 ##" + fileName);
// IE : C:/Documents and Settings/lt/桌面/abc.txt
// 其他: abc.txt -1+1
// * 获得上传文件的名称
fileName = fileName.substring(fileName.lastIndexOf(File.separator) + 1);
// * 上传文件,文件名称重复 -- 格式: UUID32_fileName
fileName = UUID.randomUUID().toString().replace("-", "") + "_" + fileName;
// 7.2上传文件内容
InputStream is = fileItem.getInputStream();
// 保存
String uploadPath = this.getServletContext().getRealPath("/upload");
OutputStream out = new FileOutputStream(new File(uploadPath,fileName));
int len = -1;
byte[] buf = new byte[1024];
while( (len = is.read(buf)) !=-1 ){
out.write(buf, 0, len);
}
out.close();
is.close(); //如果不关流,临时文件不能删除
//删除临时文件
fileItem.delete();
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
2,文件的下载
访问Servlet即可得到要下载的文件
Java代码:
package com.file.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(name = "downloadServlet", urlPatterns = { "/downloadServlet" })
public class DownloadServlet 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 fileName = "美女.jpg";
InputStream is = this.getServletContext().getResourceAsStream("/download/" + fileName);
//处理中文下载文件名称,特殊
fileName = new String(fileName.getBytes("GBK"),"ISO-8859-1");
//通过浏览器,发送的资源为下载
response.setHeader("content-disposition", "attachment;filename=" + fileName);
OutputStream out = response.getOutputStream();
int len = - 1;
byte[] buf = new byte[1024];
while( (len = is.read(buf)) != -1 ){
out.write(buf, 0, len);
}
is.close();
}
}
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/12061.html