servlet实现文件的上传与下载

servlet代码

package com.cc.uploaddownload;
 
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
 
@MultipartConfig
public class UploadDownloadServlet extends HttpServlet {
 
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(req, resp);
	}
 
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String method = req.getParameter("method");
		if (method.equals("download")) {
			this.download(req,resp);
		}
		if (method.equals("upload")) {
			this.upload(req, resp);
		}
	}
 
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		super.destroy();
	}
 
	@Override
	public void init() throws ServletException {
		// TODO Auto-generated method stub
		super.init();
	}
 
	private void upload(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("text/html;charset=UTF-8");
		// 获取上传文件域
		Part part = request.getPart("headShot");
		// 获取上传文件名称
		String fileName = part.getSubmittedFileName();
		// 为防止上传文件重名,对文件重新命名
		String newFileName = System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf("."));
		// 将上传的文件保存在服务器发布路径的application/images路径下
		// String filePath =
		// getServletContext().getRealPath("/application/images");
		String filePath = "D:/application/files";
		System.out.println(filePath);
		File f = new File(filePath);
		if (!f.exists()) {
			f.mkdirs();
		}
		part.write(filePath + "/" + newFileName);
		RequestDispatcher dispatcher = request.getRequestDispatcher("updown.jsp");
		dispatcher.forward(request, response);
 
	}
 
	private void download(HttpServletRequest request, HttpServletResponse response)
			throws IOException, ServletException {
		//得到工程的绝对路径  http://localhost:8080/UpDown
//		String path = request.getServletContext().getRealPath("/")+"images\\";
//		String path1 = request.getServletContext().getContextPath();
//		String path2 = request.getServletPath();
//		String path3 = request.getRequestURI();
//		System.out.println(path);
//		System.out.println("2:"+path1);
//		System.out.println("3:"+path2);
//		System.out.println("4:"+path3);
		
		String filename = "file.png";
		File file = new File("D:\\application\\files\\1.png");
		if (file.exists()) {
			response.setContentType("application/x-msdownload");
			response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
			InputStream inputStream = new FileInputStream(file);
			OutputStream outputStream = response.getOutputStream();
			byte[] b = new byte[1024]; 
			int n ;
			while((n = inputStream.read(b))!=-1){
				outputStream.write(b, 0, n);
			}
			outputStream.close();
			inputStream.close();
		}else{
			RequestDispatcher dispatcher = request.getRequestDispatcher("updown.jsp");
			dispatcher.forward(request, response);
		}
	}
 
}

jsp代码

<%@ page language="java" contentType="text/html; charset=GB18030"
	pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>Insert title here</title>
</head>
<body>
	<form action="UploadDownloadServlet?method=upload" method="post"
		enctype="multipart/form-data">
		<input name="headShot" id="headShot" type="file"> <input
			type="submit" value="提交">
	</form>
	<br /> 下载:
	<a href="UploadDownloadServlet?method=download">图片</a>
</body>
</html>

web.xml代码

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
  <display-name>DownLoadUpLoad</display-name>
  
    <servlet>
    <servlet-name>UploadDownloadServlet</servlet-name>
    <servlet-class>com.cc.uploaddownload.UploadDownloadServlet</servlet-class>
  </servlet>
 
  <servlet-mapping>
    <servlet-name>UploadDownloadServlet</servlet-name>
    <url-pattern>/UploadDownloadServlet</url-pattern>
  </servlet-mapping>
</web-app>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值