文件下载DEMO

java后台功能分为1上传 2列表显示 3下载 代码如下:
public class FileUpload extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 获取请求参数: 区分不同的操作类型
		String method = request.getParameter("method");
		if ("upload".equals(method)) {
			// 上传
			upload(request,response);
		}
		else if ("downList".equals(method)) {
			// 进入下载列表
			downList(request,response);
		}
		
		else if ("down".equals(method)) {
			// 下载
			down(request,response);
		}

		
	}

	public void upload(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
		try{
		//1.创建文件上传工厂对象
		FileItemFactory fac =new DiskFileItemFactory();
		//2.创建文件上传核心工具类
		ServletFileUpload upload= new ServletFileUpload(fac);
		//3 设置大小限制参数
		upload.setFileSizeMax(400*1024*1024);	// 单个文件大小限制
		upload.setSizeMax(400*1024*1024);		// 总文件大小限制
		upload.setHeaderEncoding("UTF-8");		// 对中文文件编码处理
		// 判断
		if (upload.isMultipartContent(request)) {
		// 3. 把请求数据转换为list集合
		List<FileItem> list = upload.parseRequest(request);
		// 遍历
		for (FileItem item : list){
		// 判断:普通文本数据
		if (item.isFormField()){
		// 获取名称
		String name = item.getFieldName();
		// 获取值
		String value = item.getString();
		System.out.println(value);
		} 
		// 文件表单项
		else {
		/******** 文件上传 ***********/
		// a. 获取文件名称
		String name = item.getName();
		/*String value = item.getString();
		System.out.println(value);*/
		// ----处理上传文件名重名问题----
		// a1. 先得到唯一标记
		String id = UUID.randomUUID().toString();
		// a2. 拼接文件名
		name = id + "#" + name;						
								
		// b. 得到上传目录
		String basePath = getServletContext().getRealPath("/upload");
		// c. 创建要上传的文件对象
		File file = new File(basePath,name);
		// d. 上传
		item.write(file);
		item.delete();  // 删除组件运行时产生的临时文件
			}
			}
			}
		} catch (Exception e) {
		e.printStackTrace();
		}
	}
	
	public void downList(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
		// 实现思路:先获取upload目录下所有文件的文件名,再保存;跳转到down.jsp列表展示
		
				//1. 初始化map集合Map<包含唯一标记的文件名, 简短文件名>  ;
				Map<String,String> fileNames = new HashMap<String,String>();
				
				//2. 获取上传目录,及其下所有的文件的文件名
				String bathPath = getServletContext().getRealPath("/upload");
				// 目录
				File file = new File(bathPath);
				// 目录下,所有文件名
				String list[] = file.list();
				// 遍历,封装
				if (list != null && list.length > 0){
					for (int i=0; i<list.length; i++){
						// 全名
						String fileName = list[i];
						// 短名
						String shortName = fileName.substring(fileName.lastIndexOf("#")+1);
						// 封装
						fileNames.put(fileName, shortName);
					}
				}
				
				// 3. 保存到request域
				request.setAttribute("fileNames", fileNames);
				// 4. 转发
				request.getRequestDispatcher("/downlist.jsp").forward(request, response);		
	}
	public void down(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
		// 获取用户下载的文件名称(url地址后追加数据,get) 
				String fileName = request.getParameter("fileName");
				/*fileName = new String(fileName.getBytes("ISO8859-1"),"UTF-8");*/
				String shortName = fileName.substring(fileName.lastIndexOf("#")+1);
				System.out.println(shortName);
				// 先获取上传目录路径
				String basePath = getServletContext().getRealPath("/upload");
				// 获取一个文件流
				InputStream in = new FileInputStream(new File(basePath,fileName));
				
				// 如果文件名是中文,需要进行url编码
				shortName = URLEncoder.encode(shortName, "UTF-8");
				// 设置下载的响应头
				response.setHeader("content-disposition", "attachment;fileName=" + shortName);
				
				// 获取response字节流
				OutputStream out = response.getOutputStream();
				byte[] b = new byte[1024];
				int len = -1;
				while ((len = in.read(b)) != -1){
					out.write(b, 0, len);
				}
				// 关闭
				out.close();
				in.close();
	}
	
	public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{ 
		this.doGet(request,response);
	}

}

//两个入口 一个下载一个上传。



//列表显示页面


存在服务器的文件名用UUID加了文件名前缀,保证 服务器文件名不重复。

在显示的时候用substring 将#前后截取,保证又显示的时候跟上传看到是一样的。

在下载的时候我也使用了同样的处理方法,保证下载的文件和列表中 看到的文件一样。

大部分参考的传智的课件,前端代码也发一下:

index.jsp:

<html>
  <head>    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
  </head> 
  <<body>	
  		<a href="${pageContext.request.contextPath }/upload.jsp">文件上传</a>    
  		<a href="${pageContext.request.contextPath }/FileUpload?method=downList">文件下载</a> 
  		
  </body>

</html>
upload.jsp:
<body>	
  	 <form name="frm_test" action="${pageContext.request.contextPath }/FileUpload?method=upload" method="post" enctype="multipart/form-data">
  	 	 <%--<input type="hidden" name="method" value="upload">--%>
  	 	 
  	 	 用户名:<input type="text" name="userName">  <br/>
  	 	文件:   <input type="file" name="file_img">   <br/>
  	 	
  	 	<input type="submit" value="提交">
   	 </form>
  </body>
downlist.jsp:
 <body>	
	<table border="1" align="center">
		<tr>
			<th>序号</th>
			<th>文件名</th>
			<th>操作</th>
		</tr>
		<c:forEach var="en" items="${requestScope.fileNames}" varStatus="vs">
			<tr>
				<td>${vs.count }</td>
				<td>${en.value }</td>
				<td>
					<%--<a href="${pageContext.request.contextPath }/fileServlet?method=down&..">下载</a>--%>
					<!-- 构建一个地址  -->
					<c:url var="url" value="FileUpload">
						<c:param name="method" value="down"></c:param>
						<c:param name="fileName" value="${en.key}"></c:param>
					</c:url>
					<!-- 使用上面地址 -->
					<a href="${url}" method="post">下载</a>
				</td>
			</tr>
		</c:forEach>
	</table>  		
  </body>

downlist.jsp页签上面得加上:

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>

否则会早上map数据无法显示。

还有注意servelet的配置,用框架久了,拿到这个东西都忘了页面跳转service和method的配置方法了。

架包为:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Go语言提供了多种方式来实现文件下载demo。 一种简单的实现方式是使用net/http包中的ServeFile函数来提供文件下载服务。以下是一个示例代码: ```go package main import ( "log" "net/http" ) func main() { fs := http.FileServer(http.Dir("files")) // 将files目录下的文件作为静态文件服务器 http.Handle("/files/", http.StripPrefix("/files/", fs)) // 配置路由 http.HandleFunc("/download", func(w http.ResponseWriter, r *http.Request) { filePath := "files/demo.txt" // 要下载的文件路径 http.ServeFile(w, r, filePath) }) log.Println("Listening on :8080...") err := http.ListenAndServe(":8080", nil) if err != nil { log.Fatal(err) } } ``` 在上述代码中,首先使用http.FileServer函数将files目录下的文件作为静态文件服务器,然后使用http.Handle函数配置路由,将文件服务器的处理路径配置为/files/。接着使用http.HandleFunc函数配置/download路径的处理函数,该函数调用http.ServeFile函数实现文件的下载。 另一种实现方式是使用gin框架,该框架提供了更多的功能和便捷的API。以下是一个使用gin框架实现下载文件的demo示例: ```go package main import ( "github.com/gin-gonic/gin" "log" "net/http" ) func main() { r := gin.Default() r.Static("/files", "./files") // 配置静态文件路由 r.GET("/download", func(c *gin.Context) { filePath := "files/demo.txt" // 要下载的文件路径 c.File(filePath) }) log.Println("Listening on :8080...") err := r.Run(":8080") if err != nil { log.Fatal(err) } } ``` 在上述代码中,首先使用gin.Default()初始化一个gin引擎,然后使用r.Static函数配置/files的静态文件路径。接着使用r.GET函数配置/download路径的处理函数,该函数调用c.File函数实现文件的下载。 以上就是使用Go语言实现文件下载的两种简单示例,可以根据具体需求选择适合的方式来实现文件下载服务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值