从web服务器上下载文件是如何实现的?

从web服务器上下载文件是如何实现的?,第1张

/**

 * 根据文件输入流,和文件名称下载文件

 * @param resp HttpServletResponse

 * @param file 供下载的文件

 * @param file_name 所显示的下载文件名称

 */

public void FileDownLoad(HttpServletResponse resp ,File file, String file_name) {

try {

String fileName = new String(file_name.getBytes("GBK"), "ISO8859_1")

resp.setContentType("applicationcharset=utf-8") // 指定文件的保存类型。链誉

resp.setHeader("Content-disposition", "attachment filename="+ fileName)

ServletOutputStream oupstream = resp.getOutputStream()

FileInputStream from = new FileInputStream(file)

byte[] buffer = new byte[catchSize]

int bytes_read

while ((bytes_read = from.read(buffer)) != -1) {

oupstream.write(buffer, 0, bytes_read)

}

oupstream.flush()

} catch (Exception e) {

}

}

这个是服务器辩困端文件下载工具类 题主可以试试,望采纳棚灶段

import java.io.*

import java.net.*

import java.util.Scanner

public class Test {

private static String fileName="http://localhost/file/1.jpg"

public static void main(String args[]) throws Exception 姿帆者{

URL url=new URL(fileName)

URLConnection uc=url.openConnection()

uc.connect()

HttpURLConnection huc=(HttpURLConnection)uc

if(huc.getResponseCode()!=HttpURLConnection.HTTP_OK){

//判断是否成功连接到http,如果不能连接则返回

System.out.println("can't connect")

return

}

File f=new File("D://text.jpg")//把文件复制到D盘的text.jpg中

InputStream in=(uc.getInputStream())//打开输入流

byte[] data=new byte[1024*10]

int l=in.read(data)

if(!f.exists()) 轿并f.createNewFile()

FileOutputStream out=new FileOutputStream(f)

while(l!=-1){

out.write(data, 0, l)

l=in.read(data)

}

out.flush()

out.close()

System.out.println("OK")

}

}

自己把源地址修改下迹薯


欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/tougao/12238488.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-22
下一篇 2023-05-22

发表评论

登录后才能评论

评论列表(0条)

保存