如何怎样从qq群里下载文件件

Posts - 135,
Articles - 0,
Comments - 5
12:10 by 江湖么名, ... 阅读,
利用程序自己编写下载文件挺有意思的。Python中最流行的方法就是通过Http利用urllib或者urllib2模块。当然你也可以利用ftplib从ftp站点下载文件。此外Python还提供了另外一种方法requests。
来看看三种方法是如何来下载zip文件的:
1 import urllib
2 import urllib2
3 import requests
5 url = 'http://www.blog.pythonlibrary.org/wp-content/uploads/2012/06/wxDbViewer.zip'
7 print "downloading with urllib"
8 urllib.urlretrieve(url, "code.zip")
10 print "downloading with urllib2"
11 f = urllib2.urlopen(url)
12 data = f.read()
13 with open("code2.zip", "wb") as code:
code.write(data)
16 print "downloading with requests"
17 r = requests.get(url)
18 with open("code3.zip", "wb") as code:
code.write(r.content)看起来使用urllib最为简单,一句语句即可。当然你可以把urllib2缩写成:
1 f = urllib2.urlopen(url) with open("code2.zip", "wb") as code:
2 code.write(f.read())
具体点的可以看看:http://www.blog.pythonlibrary.org//python-101-how-to-download-a-file/温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!&&|&&
LOFTER精选
网易考拉推荐
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
七.有人问,把2007版本的 word 文档U盘拿到打印店打印,却打印不出来。什么原因。经了解,现在大部份打印店打印的仍然是97—2003版本。低版本不能转化为高版本,当然无法打印。建议打印之前,先在自己的电脑上把该文档另存为97——2003版本。连文件内容一起另存为桌面,(注;不属于创建桌面快捷图标)。然后复制粘贴到U盘,才到打印店打印。方法是,打开该文档,检查一遍,然后单击左上方的office 按钮,在弹出的页面中单击左侧的“另存为”按钮,接着单击右侧的“word 97——2003 文档”按钮。在弹出的另存为对话框最上方“库”的左侧单击下拉箭头▼,在弹出的列表中单击“桌面”,单击右下角的“保存”按钮,在桌面就能看到连内容一起另存的该图标,然后再复制粘贴到U盘,拿到打印店打印。见图-8和图-9:
& && & &&&&&&
阅读(4434)|
用微信&&“扫一扫”
将文章分享到朋友圈。
用易信&&“扫一扫”
将文章分享到朋友圈。
历史上的今天
在LOFTER的更多文章
loftPermalink:'',
id:'fks_',
blogTitle:'如何找到已下载文件(夹)的路径',
blogAbstract:'如何找到已下载文件(夹)的路径\n\n我们有时候下载一个文件,下载完后却找不到它存放在什么地方(即它的路',
blogTag:'',
blogUrl:'blog/static/',
isPublished:1,
istop:false,
modifyTime:6,
publishTime:9,
permalink:'blog/static/',
commentCount:17,
mainCommentCount:17,
recommendCount:4,
bsrk:-100,
publisherId:0,
recomBlogHome:false,
currentRecomBlog:false,
attachmentsFileIds:[],
groupInfo:{},
friendstatus:'none',
followstatus:'unFollow',
pubSucc:'',
visitorProvince:'',
visitorCity:'',
visitorNewUser:false,
postAddInfo:{},
mset:'000',
remindgoodnightblog:false,
isBlackVisitor:false,
isShowYodaoAd:false,
hostIntro:'',
hmcon:'1',
selfRecomBlogCount:'0',
lofter_single:''
{list a as x}
{if x.moveFrom=='wap'}
{elseif x.moveFrom=='iphone'}
{elseif x.moveFrom=='android'}
{elseif x.moveFrom=='mobile'}
${a.selfIntro|escape}{if great260}${suplement}{/if}
{list a as x}
推荐过这篇日志的人:
{list a as x}
{if !!b&&b.length>0}
他们还推荐了:
{list b as y}
转载记录:
{list d as x}
{list a as x}
{list a as x}
{list a as x}
{list a as x}
{if x_index>4}{break}{/if}
${fn2(x.publishTime,'yyyy-MM-dd HH:mm:ss')}
{list a as x}
{if !!(blogDetail.preBlogPermalink)}
{if !!(blogDetail.nextBlogPermalink)}
{list a as x}
{if defined('newslist')&&newslist.length>0}
{list newslist as x}
{if x_index>7}{break}{/if}
{list a as x}
{var first_option =}
{list x.voteDetailList as voteToOption}
{if voteToOption==1}
{if first_option==false},{/if}&&“${b[voteToOption_index]}”&&
{if (x.role!="-1") },“我是${c[x.role]}”&&{/if}
&&&&&&&&${fn1(x.voteTime)}
{if x.userName==''}{/if}
网易公司版权所有&&
{list x.l as y}
{if defined('wl')}
{list wl as x}{/list}Android中如何实现文件下载
最近做一个项目需要从服务器下载图片到本地sdcard,上网查找了一些例子,下面这个比较合适,原文内容如下:
我们在开发中经常需要从服务器下载文件,下载的内容可能有交换的信息,缓存的图片,程序更新包等。我们使用URLConnection来实现下载。先看几行代码:
String urlDownload = "";
urlDownload =
"/img/baidu_sylogo1.gif";
URL url = new URL(urlDownload );
// 打开连接 &&
URLConnection con = url.openConnection();
// 输入流 &&
InputStream is = con.getInputStream();
如上面的代码所示,指定一个下载的目标链接,我们上面指定了一个图片地址。然后构建一个URL对象,调用该
对象的openConnection方法来建立一个数据通路(连接)。代码的最后一行使用
con.getInputStream,拿到一个输入流对象,通过这个流对象我们就可以读取到这个文件的内容了。下面要做的,就是读取这个流,将流写入我
们的本地文件。不过在这之前,我们还要说下这个方法:
xmlns="http://www.w3.org/1999/xhtml"&//获得文件的长度
int contentLength = con.getContentLength();
System.out.println("长度
:"+contentLength)&/span&
获得文件长度的方法。ContentLength是不很熟啊。它是http协议里描述头(head)部分的描述属性之一。实际这里是发送了一个http请求,分析了返回(response)里数据内容。
我们常常会把文件下载到手机的存储卡里,所以还会用到获得存储卡路径的方法:
xmlns="http://www.w3.org/1999/xhtml"&// 获得存储卡路径,构成
保存文件的目标路径
String dirName = "";
Environment.getExternalStorageDirectory()+"/MyDownload/";
File f = new File(dirName);
if(!f.exists())
& & f.mkdir();
Environment.getExternalStorageDirectory()
方法会返回一个字符串,指示了存储卡的路径。我们拼接字符串出一个准备存放下载文件的文件夹。并先判断文件夹是是否存在,如果不存在,则新建一个文件夹。
做完了上面的准备后,基本就能实现下载了。我们看看主要的完整代码。
下载前的准备工作:
//要下载的文件路径
String urlDownload = "";
//urlDownload =
&"http://192.168.3.39/text.txt";
urlDownload =
"/img/baidu_sylogo1.gif";
// 获得存储卡路径,构成 保存文件的目标路径
String dirName = "";
Environment.getExternalStorageDirectory()+"/MyDownload/";
File f = new File(dirName);
if(!f.exists())
& & f.mkdir();
下载的操作:
//准备拼接新的文件名(保存在存储卡后的文件名)
String newFilename =
_urlStr.substring(_urlStr.lastIndexOf("/")+1);
newFilename = _dirName + newF
File file = new File(newFilename);
//如果目标文件已经存在,则删除。产生覆盖旧文件的效果
if(file.exists())
& & file.delete();
& &// 构造URL
& &URL url = new URL(_urlStr);
& &// 打开连接
& &URLConnection con =
url.openConnection();
& &//获得文件的长度
& &int contentLength =
con.getContentLength();
& &System.out.println("长度
:"+contentLength);
& &// 输入流
& &InputStream is =
con.getInputStream(); &
& &// 1K的数据缓冲
& &byte[] bs = new byte[1024];
& &// 读取到的数据长度
& &// 输出的文件流
& &OutputStream os = new
FileOutputStream(newFilename);
& &// 开始读取
& &while ((len = is.read(bs)) !=
&os.write(bs, 0, len);
& &// 完毕,关闭所有链接
& &os.close();
& &is.close();
} catch (Exception e) {
& e.printStackTrace();
我的部分代码如下:
//从服务器下载图片到本地
& & private void
getPhotoFromServer(List&Advert&
& & //读取服务器ip地址
& & String serverip =
NetworkUtil.getDns(); //直接读取服务器的ip地址
& & //String serverURL =
serverURLAll.substring(serverURLAll.indexOf(":")+3,
serverURLAll.lastIndexOf(":")); //最好还是直接从数据库或者其他地方读取ip地址
& & Log.d(TAG, "server ip is
" + serverip);
& & //整合成完整的广告图片存放地址目录
& & String urlDownload =
"http://" + serverip +":8080/proPicRecord/";
& & //广告图片本地sd卡存放目录
& & String dirName =
"/sdcard/advert/";
//判断本地存放广告图片的目录是否存,不存在则新建文件夹
& & File f = new
File(dirName);
& & if(!f.exists())
&f.mkdir();
//服务器上广告图片完整路径名,供下载用
& & String urlDownloadAll =
//准备拼接新的文件名(保存在存储卡后的文件名)
& & for(int i=0;
adverts!=null &&
i&adverts.size(); i++){
& & & Advert
advert = adverts.get(i);
//下载路径添加上广告图片名字
urlDownloadAll = urlDownload + advert.getUrl();
& & & Log.d(TAG,
"The whole server download url is " + urlDownloadAll);
//获取广告图片的名字,其实使用advert.getUrl()也可
& & String newFilename =
urlDownloadAll.substring(urlDownloadAll.lastIndexOf("/")+1);
& & //本地播放广告图片的完整路径
& & newFilename = dirName +
& & Log.d(TAG, "The local
url is" + newFilename);
& & File file = new
File(newFilename);
//如果目标文件已经存在,则删除,产生覆盖旧文件的效果(此处以后可以扩展为已经存在图片不再重新下载功能)
& & if(file.exists())
&file.delete();
& & try{ &
& & //构造URL
& & &URL url =
new URL(urlDownloadAll);
&//打开连接
&URLConnection con = url.openConnection();
&//获得文件的长度
& & &//int
contentLength = con.getContentLength();
&//System.out.println("长度 :"+contentLength);
& & &//输入流
& & &InputStream
is = con.getInputStream();
&//1K的数据缓冲
& & &byte[] bs =
new byte[1024];
&//读取到的数据长度
&//输出的文件流
&OutputStream os = new
FileOutputStream(newFilename);
&//开始读取
& & &while ((len
= is.read(bs)) != -1) {
& &os.write(bs, 0, len);
&//完毕,关闭所有链接
&os.close();
&is.close();
& & }catch(Exception
e.printStackTrace();
已投稿到:
以上网友发言只代表其个人观点,不代表新浪网的观点或立场。&nbsp&#8250&nbsp&nbsp&#8250&nbsp
android中如何下载文件并显示下载进度
最近开发中遇到需要下载文件的问题,对于一般的下载来说不用考虑断点续传,不用考虑多个线程,比如下载一个apk之类的,这篇文章讨论的就是这种情形。这里主要讨论三种方式:AsyncTask、Service和使用DownloadManager。一、使用AsyncTask并在进度对话框中显示下载进度这种方式的优势是你可以在后台执行下载任务的同时,也可以更新UI(这里我们用progress bar来更新下载进度)
下面的代码是使用的例子// declare the dialog as a member field of your activity
ProgressDialog mProgressD
// instantiate it within the onCreate method
mProgressDialog = new ProgressDialog(YourActivity.this);
mProgressDialog.setMessage("A message");
mProgressDialog.setIndeterminate(true);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(true);
// execute this when the downloader must be fired
final DownloadTask downloadTask = new DownloadTask(YourActivity.this);
downloadTask.execute("the url to the file you want to download");
mProgressDialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
downloadTask.cancel(true);
});DownloadTask继承自AsyncTask,按照如下框架定义,你需要将代码中的某些参数替换成你自己的。// usually, subclasses of AsyncTask are declared inside the activity class.
// that way, you can easily modify the UI thread from here
private class DownloadTask extends AsyncTask&String, Integer, String& {
private PowerManager.WakeLock mWakeL
public DownloadTask(Context context) {
this.context =
protected String doInBackground(String... sUrl) {
InputStream input =
OutputStream output =
HttpURLConnection connection =
URL url = new URL(sUrl[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
// expect HTTP 200 OK, so we don't mistakenly save error report
// instead of the file
if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
return "Server returned HTTP " + connection.getResponseCode()
+ " " + connection.getResponseMessage();
// this will be useful to display download percentage
// might be -1: server did not report the length
int fileLength = connection.getContentLength();
// download the file
input = connection.getInputStream();
output = new FileOutputStream("/sdcard/file_name.extension");
byte data[] = new byte[4096];
long total = 0;
while ((count = input.read(data)) != -1) {
// allow canceling with back button
if (isCancelled()) {
input.close();
// publishing the progress....
if (fileLength & 0) // only if total length is known
publishProgress((int) (total * 100 / fileLength));
output.write(data, 0, count);
} catch (Exception e) {
return e.toString();
} finally {
if (output != null)
output.close();
if (input != null)
input.close();
} catch (IOException ignored) {
if (connection != null)
connection.disconnect();
}上面的代码只包含了doInBackground,这是执行后台任务的代码块,不能在这里做任何的UI操作,但是onProgressUpdate和onPreExecute是运行在UI线程中的,所以我们应该在这两个方法中更新progress bar。接上面的代码:@Override
protected void onPreExecute() {
super.onPreExecute();
// take CPU lock to prevent CPU from going off if the user
// presses the power button during download
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
mWakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
getClass().getName());
mWakeLock.acquire();
mProgressDialog.show();
protected void onProgressUpdate(Integer... progress) {
super.onProgressUpdate(progress);
// if we get here, length is known, now set indeterminate to false
mProgressDialog.setIndeterminate(false);
mProgressDialog.setMax(100);
mProgressDialog.setProgress(progress[0]);
protected void onPostExecute(String result) {
mWakeLock.release();
mProgressDialog.dismiss();
if (result != null)
Toast.makeText(context,"Download error: "+result, Toast.LENGTH_LONG).show();
Toast.makeText(context,"File downloaded", Toast.LENGTH_SHORT).show();
}注意需要添加如下权限:&uses-permission android:name="android.permission.WAKE_LOCK" /&二、在service中执行下载在service中执行下载任务的麻烦之处在于如何通知activity更新UI。下面的代码中我们将用ResultReceiver和IntentService来实现下载。ResultReceiver允许我们接收来自service中发出的广播,IntentService继承自service,这IntentService中我们开启一个线程开执行下载任务(service和你的app其实是在一个线程中,因此不想阻塞主线程的话必须开启新的线程)。public class DownloadService extends IntentService {
public static final int UPDATE_PROGRESS = 8344;
public DownloadService() {
super("DownloadService");
protected void onHandleIntent(Intent intent) {
String urlToDownload = intent.getStringExtra("url");
ResultReceiver receiver = (ResultReceiver) intent.getParcelableExtra("receiver");
URL url = new URL(urlToDownload);
URLConnection connection = url.openConnection();
connection.connect();
// this will be useful so that you can show a typical 0-100% progress bar
int fileLength = connection.getContentLength();
// download the file
InputStream input = new BufferedInputStream(connection.getInputStream());
OutputStream output = new FileOutputStream("/sdcard/BarcodeScanner-debug.apk");
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
// publishing the progress....
Bundle resultData = new Bundle();
resultData.putInt("progress" ,(int) (total * 100 / fileLength));
receiver.send(UPDATE_PROGRESS, resultData);
output.write(data, 0, count);
output.flush();
output.close();
input.close();
} catch (IOException e) {
e.printStackTrace();
Bundle resultData = new Bundle();
resultData.putInt("progress" ,100);
receiver.send(UPDATE_PROGRESS, resultData);
}注册DownloadService:&service android:name=".DownloadService"/&activity中这样调用DownloadService// initialize the progress dialog like in the first example
// this is how you fire the downloader
mProgressDialog.show();
Intent intent = new Intent(this, DownloadService.class);
intent.putExtra("url", "url of the file to download");
intent.putExtra("receiver", new DownloadReceiver(new Handler()));
startService(intent);使用ResultReceiver接收来自DownloadService的下载进度通知private class DownloadReceiver extends ResultReceiver{
public DownloadReceiver(Handler handler) {
super(handler);
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
if (resultCode == DownloadService.UPDATE_PROGRESS) {
int progress = resultData.getInt("progress");
mProgressDialog.setProgress(progress);
if (progress == 100) {
mProgressDialog.dismiss();
}2.1使用 Groundy library 可以帮助你在后台service中运行一些代码,其实也是基于刚刚用到的 ResultReceiver,下面是使用Groundy的大致代码:public class MainActivity extends Activity {
private ProgressDialog mProgressD
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
findViewById(R.id.btn_download).setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String url = ((EditText) findViewById(R.id.edit_url)).getText().toString().trim();
Bundle extras = new Bundler().add(DownloadTask.PARAM_URL, url).build();
Groundy.create(DownloadExample.this, DownloadTask.class)
.receiver(mReceiver)
.params(extras)
mProgressDialog = new ProgressDialog(MainActivity.this);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
private ResultReceiver mReceiver = new ResultReceiver(new Handler()) {
protected void onReceiveResult(int resultCode, Bundle resultData) {
super.onReceiveResult(resultCode, resultData);
switch (resultCode) {
case Groundy.STATUS_PROGRESS:
mProgressDialog.setProgress(resultData.getInt(Groundy.KEY_PROGRESS));
case Groundy.STATUS_FINISHED:
Toast.makeText(DownloadExample.this, R.string.file_downloaded, Toast.LENGTH_LONG);
mProgressDialog.dismiss();
case Groundy.STATUS_ERROR:
Toast.makeText(DownloadExample.this, resultData.getString(Groundy.KEY_ERROR), Toast.LENGTH_LONG).show();
mProgressDialog.dismiss();
}其中GroundyTask的定义如下:public class DownloadTask extends GroundyTask {
public static final String PARAM_URL = "com.groundy.sample.param.url";
protected boolean doInBackground() {
String url = getParameters().getString(PARAM_URL);
File dest = new File(getContext().getFilesDir(), new File(url).getName());
DownloadUtils.downloadFile(getContext(), url, dest, DownloadUtils.getDownloadListenerForTask(this));
} catch (Exception pokemon) {
}但是请记住要在activity中注册了相关service才行:&service android:name="com.codeslap.groundy.GroundyService"/&三、使用DownloadManager其实这才是解决下载问题的终极方法,因为他使用起来实在是太简单了。可惜只有在GingerBread 之后才能使用。先判断能不能使用DownloadManager:/**
* @param context used to check the device version and DownloadManager information
* @return true if the download manager is available
public static boolean isDownloadManagerAvailable(Context context) {
if (Build.VERSION.SDK_INT & Build.VERSION_CODES.GINGERBREAD) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName("com.android.providers.downloads.ui", "com.android.providers.downloads.ui.DownloadList");
List&ResolveInfo& list = context.getPackageManager().queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() & 0;
} catch (Exception e) {
}如果能,那么只需要这样就可以开始下载一个文件了:String url = "url you want to download";
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setDescription("Some descrition");
request.setTitle("Some title");
// in order for this if to run, you must use the android 3.2 to compile your app
if (Build.VERSION.SDK_INT &= Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, "name-of-the-file.ext");
// get download service and enqueue file
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);下载的进度会在消息通知中显示。总结前两种方法需要你考虑的东西很多,除非是你想完全控制下载的整个过程,否则用最后一种比较省事。
上一篇: 我们每天都在安装和卸载APK(安卓应用程序包文件),或许一天会有好几次,但是你有想过下面问题吗? 什么是Package Manager(包管理器)和Package Installer(程序安装包)? APK文件保存在Android的哪个地方? APK文件安装过程的细节是怎样的? Package Man
下一篇: 转自: eclipse_xu 的博客 不知从某某时间开始,这种效果开始在UI设计中流行起来了,让我们先来看看效果: 大家在支付宝、美团等很多App中都有使用,要实现这个效果,我们可以来分析下思路: 我们肯定要用2个一样的布局来显示我们的粘至布局,一个是正常的、

我要回帖

更多关于 苹果如何下载文件 的文章

 

随机推荐