淘先锋技术网

首页 1 2 3 4 5 6 7

Java Web 开发中,文件上传和下载功能是常见需求。本文将介绍如何实现 Java Web 中的文件上传和下载功能。

文件上传

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");//设置响应的字符集
//判断是否为文件上传请求
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if (isMultipart) {
//创建文件上传对象
ServletFileUpload fileUpload = new ServletFileUpload();
try {
//解析请求
FileItemIterator iterator = fileUpload.getItemIterator(request);
while (iterator.hasNext()) {
FileItemStream fileItem = iterator.next();
//判断是否为文件域
if (!fileItem.isFormField()) {
//获取上传文件的名称
String fileName = fileItem.getName();
//处理文件上传
byte[] buffer = new byte[1024];
InputStream inputStream = fileItem.openStream();
OutputStream outputStream = new FileOutputStream(new File("d:\\" + fileName));
int length = 0;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
}
}
response.getWriter().print("");
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}

文件下载

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String fileName = request.getParameter("fileName");//获取下载文件名
//设置响应头
response.setContentType("application/octet-stream;charset=utf-8");
response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
//获取文件流
InputStream inputStream = new FileInputStream("d:\\" + fileName);
OutputStream outputStream = response.getOutputStream();
byte[] buffer = new byte[1024];
int length = 0;
while ((length = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, length);
}
outputStream.close();
inputStream.close();
}

以上就是 Java Web 中实现文件上传和下载的相关代码,希望对大家有所帮助。