日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java下载文件

發布時間:2025/5/22 编程问答 15 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java下载文件 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

java下載文件
只是普及:如果下載的文件是壓縮文件 給該文件添加超鏈接會直接下載 如果是圖片 視頻 則需要以下代碼
java頁面

package cn.ybzy.mvcproject.utils;import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.PrintWriter;import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;/*** Servlet implementation class DownLoad*/ @WebServlet("/DownLoad") public class DownLoad extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public DownLoad() {super();// TODO Auto-generated constructor stub}/*** @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)*/protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// TODO Auto-generated method stubString filename = request.getParameter("filename");response.setContentType("application/octet-stream");response.setCharacterEncoding("utf-8");response.setHeader("Content-Disposition", "attachment;filename=" + filename);OutputStream write= response.getOutputStream();String path = request.getServletContext().getRealPath(File.separatorChar+"down"+File.separatorChar+filename);InputStream in=new FileInputStream(path);byte[] buffer=new byte[1024];int len=0;int i=0;while ((i = in.read(buffer)) != -1) {write.write(buffer, 0, i);write.flush();} }}

jsp頁面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><base href="<%=basePath%>"><title>下載測試</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body><h1>servlet下載</h1><div><a href="${pageContext.request.contextPath}/DownLoad?filename=a.jpg">a.jpg下載</a><br><a href="${pageContext.request.contextPath}/DownLoad?filename=b.zip">b.zip下載</a></div></body> </html>

總結

以上是生活随笔為你收集整理的java下载文件的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。