当前位置:首页 » 编程语言 » java文件与下载

java文件与下载

发布时间: 2022-08-31 20:51:13

1. 用java实现文件的上传与下载

1.下载简单,无非是把服务器上的文件或者数据库中的BLob(或其他二进制型),用流读出来,然后写到客户端即可,要注意 ContentType。

2.上传,可以用Apache Commons Upload等开源工具,或者自己写:
form要用enctype="multipart/form-data"
然后服务器端也是用IO把客户端提交的文件流读入,然后写到服务器的文件系统或者数据库里。不同的数据库对Lob字段操作可能有所不同,建议用Hibernate,JPA等成熟的ORM框架,可以不考虑数据库细节。

2. java 文件和图片下载处理

用<a>标签把你的图片当作链接的形式包起来,然后点击的时候下载的href属性地址里的文件类容指向你服务器上的文件

3. java实现文件的上传和下载

用输出流 接受 一个下载地址的网络流
然后将这个输出流 保存到本地一个文件 后缀与下载地址的后缀相同··

上传的话 将某个文件流 转成字节流 上传到某个webservice方法里

-------要代码来代码

URL url=new URL("http://www..com/1.rar");
URLConnection uc=url.openConnection();
InputStream in=uc.getInputStream();
BufferedInputStream bis=new BufferedInputStream(in);
FileOutputStream ft=new FileOutputStream("E://1.rar");

这是下载 上传太麻烦就不给写了

4. 通过java实现文件下载

在jsp/servlet中断点/多线程下载文件
<%@ page import="java.io.File" %><%@ page import="java.io.IOException" %><%@ page import="java.io.OutputStream" %><%@ page import="java.io.RandomAccessFile" %><%! public void downloadFile(HttpServletRequest request, HttpServletResponse response, File file) throws IOException { RandomAccessFile raf = new RandomAccessFile(file, "r"); java.io.FileInputStream fis = new java.io.FileInputStream(raf.getFD()); response.setHeader("Server", "www.trydone.com"); response.setHeader("Accept-Ranges", "bytes"); long pos = 0; long len; len = raf.length(); if (request.getHeader("Range") != null) { response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT); pos = Long.parseLong(request.getHeader("Range") .replaceAll("bytes=", "") .replaceAll("-", "") ); } response.setHeader("Content-Length", Long.toString(len - pos)); if (pos != 0) { response.setHeader("Content-Range", new StringBuffer() .append("bytes ") .append(pos) .append("-") .append(Long.toString(len - 1)) .append("/") .append(len) .toString() ); } response.setContentType("application/octet-stream"); response.setHeader("Content-Disposition", new StringBuffer() .append("attachment;filename=\"") .append(file.getName()) .append("\"").toString()); raf.seek(pos); byte[] b = new byte[2048]; int i; OutputStream outs = response.getOutputStream(); while ((i = raf.read(b)) != -1) { outs.write(b, 0, i); } raf.close(); fis.close(); }%><% String filePath = request.getParameter("file"); filePath = application.getRealPath(filePath); File file = new File(filePath); downloadFile(request, response, file);%>
是否可以解决您的问题?

5. Java文件下载怎么实现的

下载就很简单了
把你要下载的文件做成超级链接,可以不用任何组件
比如说
下载一个word文档
<a href="名称.doc">名称.doc</a>
路径你自己写
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URI;
import java.net.URL;
import java.util.Random;
/**
*
* 实现了下载的功能*/

public class SimpleTh {

public static void main(String[] args){
// TODO Auto-generated method stub
//String path = "http://www.7cd.cn/QingTengPics/倩女幽魂.mp3";//MP3下载的地址
String path ="http://img.99luna.com/music/%CF%EB%C4%E3%BE%CD%D0%B4%D0%C5.mp3";

try {
new SimpleTh().download(path, 3); //对象调用下载的方法
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

}
public static String getFilename(String path){//获得文件的名字
return path.substring(path.lastIndexOf('/')+1);
}

public void download(String path,int threadsize) throws Exception//下载的方法
{//参数 下载地址,线程数量

URL url = new URL(path);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();//获取HttpURLConnection对象
conn.setRequestMethod("GET");//设置请求格式,这里是GET格式
conn.setReadTimeout(5*1000);//
int filelength = conn.getContentLength();//获取要下载文件的长度
String filename = getFilename(path);
File saveFile = new File(filename);
RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
accessFile.setLength(filelength);
accessFile.close();
int block = filelength%threadsize ==0?filelength/threadsize:filelength/threadsize+1;
for(int threadid = 0;threadid<=threadsize;threadid++){

new DownloadThread(url,saveFile,block,threadid).start();
}

}
private final class DownloadThread extends Thread{
private URL url;
private File saveFile;
private int block;//每条线程下载的长度
private int threadid;//线程id

public DownloadThread(URL url,File saveFile,int block,int threadid){
this.url = url;
this.saveFile= saveFile;
this.block = block;
this.threadid = threadid;
}

@Override
public void run() {
//计算开始位置的公式:线程id*每条线程下载的数据长度=?
//计算结束位置的公式:(线程id+1)*每条线程下载数据长度-1=?
int startposition = threadid*block;
int endposition = (threadid+1)*block-1;
try {
try {
RandomAccessFile accessFile = new RandomAccessFile(saveFile, "rwd");
accessFile.seek(startposition);//设置从什么位置写入数据
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod("GET");
conn.setReadTimeout(5*1000);
conn.setRequestProperty("Range","bytes= "+startposition+"-"+endposition);
InputStream inStream = conn.getInputStream();
byte[]buffer = new byte[1024];
int len = 0;
while((len = inStream.read(buffer))!=-1){
accessFile.write(buffer, 0, len);
}
inStream.close();
accessFile.close();
System.out.println("线程id:"+threadid+"下载完成");

} catch (FileNotFoundException e) {

e.printStackTrace();
}
} catch (IOException e) {

e.printStackTrace();
}

}

}
}

6. 求问Java文件下载的几种方式

InputStream fis = new BufferedInputStream(new FileInputStream(path));byte[] buffer = new byte[fis.available()];fis.read(buffer);fis.close();// 清空responseresponse.reset();// 设置response的Headerresponse.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));response.addHeader("Content-Length", "" + file.length());OutputStream toClient = new BufferedOutputStream(response.getOutputStream());response.setContentType("application/octet-stream");toClient.write(buffer);toClient.flush();toClient.close();} catch (IOException ex) {ex.printStackTrace();}return response;}public void downloadLocal(HttpServletResponse response) throws FileNotFoundException {// 下载本地文件String fileName = "Operator.doc".toString(); // 文件的默认保存名// 读到流中InputStream inStream = new FileInputStream("c:/Operator.doc");// 文件的存放路径// 设置输出的格式response.reset();response.setContentType("bin");response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");// 循环取出流中的数据byte[] b = new byte[100];int len;try {while ((len = inStream.read(b)) > 0)response.getOutputStream().write(b, 0, len);inStream.close();} catch (IOException e) {e.printStackTrace();}}public void downloadNet(HttpServletResponse response) throws MalformedURLException {// 下载网络文件int bytesum = 0;int byteread = 0;URL url = new URL("windine.blogdriver.com/logo.gif");try {URLConnection conn = url.openConnection();InputStream inStream = conn.getInputStream();FileOutputStream fs = new FileOutputStream("c:/abc.gif");byte[] buffer = new byte[1204];int length;while ((byteread = inStream.read(buffer)) != -1) {bytesum += byteread;System.out.println(bytesum);fs.write(buffer, 0, byteread);}} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}} //支持在线打开文件的一种方式public void downLoad(String filePath, HttpServletResponse response, boolean isOnLine) throws Exception {File f = new File(filePath);if (!f.exists()) {response.sendError(404, "File not found!");return;}BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));byte[] buf = new byte[1024];int len = 0;response.reset(); // 非常重要if (isOnLine) { // 在线打开方式URL u = new URL("file:///" + filePath);response.setContentType(u.openConnection().getContentType());response.setHeader("Content-Disposition", "inline; filename=" + f.getName());// 文件名应该编码成UTF-8} else { // 纯下载方式response.setContentType("application/x-msdownload");response.setHeader("Content-Disposition", "attachment; filename=" + f.getName());}OutputStream out = response.getOutputStream();while ((len = br.read(buf)) > 0)out.write(buf, 0, len);br.close();out.close();}

7. JAVA 文件下载问题

如果是本地服务器的话,应该把文件发布,会生成一个url ,用这个url就可以下载了。

8. 用java实现文件的下载,如何提高下载速度(非web开发)

下面贴出的代码是一个简单的读取远程文件保存到本地的实现,至于提高下载速度你可以利用多线程,具体可参考最下面的那个网址——

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class DownloadTester {
public static void main(String[] args) throws IOException {
String urlStr = "https://gss0.bdstatic.com/70cFsjip0QIZ8tyhnq/img/logo-.gif";
String path = "D:/";

String name = urlStr.substring(urlStr.trim().lastIndexOf("/"));

URL url = new URL(urlStr);
InputStream in = url.openConnection().getInputStream();

File file = new File(path + name);
FileOutputStream out = new FileOutputStream(file, true);

int counter = 0;
int ch;
byte[] buffer = new byte[1024];
while ((ch = in.read(buffer)) != -1) {
out.write(buffer, 0, ch);
counter += ch;

System.out.println(counter + ":byte");
}
out.flush();
in.close();
out.close();
}
}

9. java如何实现文件上传和下载的功能

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.*;
import net.sf.json.JSONObject;
import action.StudentAction;
public class UploadServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
boolean result=true;
SmartUpload mySmartUpload=new SmartUpload();
mySmartUpload.initialize(this.getServletConfig(), request,response);
mySmartUpload.setTotalMaxFileSize(50*1024*1024);//大小限制
mySmartUpload.setAllowedFilesList("doc,docx");//后缀名限制
try {
mySmartUpload.upload();
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
myFile.saveAs("/file/"+1+".doc");//保存目录
} catch (SmartUploadException e) {
e.printStackTrace();result=false;
}
//*****************************//
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Cache-Control","no-cache");
PrintWriter out = response.getWriter();
out.print(result);
out.flush();
out.close();
}
}

//我这是ajax方式的,不想这样,把//**********************//以下部分修改就行了
//需要SmartUpload组件,去网上下个就行了,也有介绍的

热点内容
数据库设计主要内容 发布:2025-01-16 05:02:02 浏览:12
存储过程如何修改 发布:2025-01-16 05:01:55 浏览:633
照片压缩包 发布:2025-01-16 04:56:56 浏览:742
手机存储用到多少最好 发布:2025-01-16 04:56:19 浏览:781
ftp站点不能启动 发布:2025-01-16 04:55:31 浏览:54
pythonip合法性 发布:2025-01-16 04:48:52 浏览:75
锂电池用3a的充电器是什么配置 发布:2025-01-16 04:26:43 浏览:35
好配置为什么感觉打联盟不流畅 发布:2025-01-16 04:23:02 浏览:900
我的世界java编辑服务器信息 发布:2025-01-16 04:21:42 浏览:507
android拨号上网 发布:2025-01-16 04:13:25 浏览:97