通过传入的一个下载路径得到server上包的大小

HTTPSession = InternetOpen("Mozilla/4.0 (compatible)", INTERNET_OPEN_TYPE_DIRECT, NULL, NULL, 0);

HTTPConnect = InternetConnect(HTTPSession,RemoteHost,RemotePort,NULL,NULL,INTERNET_SERVICE_HTTP, 0, 0);

HTTPRequest = HttpOpenRequest(HTTPConnect,"GET",FileName, "HTTP/1.1", NULL,NULL,INTERNET_FLAG_RELOAD,0);

HttpSendRequest(HTTPRequest, NULL, 0, NULL, 0);

HttpQueryInfo(HTTPRequest,HTTP_QUERY_CONTENT_LENGTH,Buffer, &BufLen,&dwIndex);

RemoteFileSize = atol(Buffer);


DWORD dwfilesize = 0;
	DWORD dwSizebuff = sizeof(dwfilesize);
	DWORD dwIndex=0;
	BOOL bQuery = ::HttpQueryInfo(m_hRequest,
		            HTTP_QUERY_CONTENT_LENGTH
					|HTTP_QUERY_FLAG_NUMBER, 
					(LPVOID)&dwfilesize/*bufQuery*/, 
					&dwSizebuff,
					&dwIndex) ;


	if (!bQuery)
	{
		OutputDebugString(_T("bQuery failed. the dwfilesize == 0\n"));
		return 0;
	}
	   return dwfilesize;


当然可以,下面是一个更为全面的方法,包含了通过Response返回文件给前端,同时也处理了常见的异常情况: ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; import javax.servlet.http.HttpServletResponse; public class FileDownloadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String fileName = request.getParameter("filename"); // 假设前端传入文件名 String filePath = "/path/to/files/" + fileName; // 文件的实际路径 try { // 创建URL对象 URL url = new URL(filePath); // 打开连接 HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); // 请求文件 conn.setDoOutput(true); // 设置允许输出 // 设置响应头 response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // 开始接收输出流 OutputStream outputStream = response.getOutputStream(); InputStream inputStream = conn.getInputStream(); byte[] buffer = new byte[1024]; // 块大小 int length; while ((length = inputStream.read(buffer)) > 0) { outputStream.write(buffer, 0, length); } // 关闭流并断开连接 outputStream.flush(); outputStream.close(); inputStream.close(); conn.disconnect(); } catch (MalformedURLException e) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid file path or URL."); e.printStackTrace(); } catch (IOException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "An error occurred during the file download."); e.printStackTrace(); } } } // 当前端访问/download?filename=your_file.txt时,就会触发这个下载请求 ``` 这个Servlet会在接收到GET请求后尝试从指定的URL下载文件,并将结果返回给前端。如果发生URL无效、IO错误或其他异常,它会返回适当的HTTP状态码和错误信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值