在 Android Lollipop 网页 View 中,我想让用户下载生成的 txt 文件:
// Store some text in a data URL.
var dataUrl = (window.URL || window.webkitURL).createObjectURL(
new Blob(["Hello world. :)"]));
// Create a link that lets the user download the text file as hello.txt.
var downloadLink = document.createElement('a');
downloadLink.setAttribute('href', dataUrl);
downloadLink.innerHTML = 'Click to download.';
// Working with David on this. I did the same thing.
// Fyi, setting the 'download' attribute just makes hitting the link
// nop, ie. do nothing at all in the web view, so I omitted it.
// - John
// Display the link.
document.getElementById('container').appendChild(downloadLink);
在Android java端,我写了一个DownloadListener尝试使用 DownloadManager 下载文件:
package com.somesideprojects;
import android.webkit.DownloadListener;
/**
* A download listener that lets users download files from the web view.
*/
public class CustomDownloadListener implements DownloadListener {
private MainActivity currentActivity;
@Override
public void onDownloadStart(
String url,
String userAgent,
String contentDisposition,
String mimeType,
long contentLength) {
android.util.Log.d("Logger",
"url : " + url +
" userAgent: " + userAgent +
" contentDisposition: " + contentDisposition +
" mimeType: " + mimeType + " contentLength " + contentLength);
android.net.Uri source = android.net.Uri.parse(url);
// Make a new request.
android.app.DownloadManager.Request request =
new android.app.DownloadManager.Request(source);
// Appears the same in notification bar while downloading.
String filename = getFilename(contentDisposition);
request.setDescription(
"This project will be saved in your downloads folder as " + filename + ".");
request.setTitle(filename);
// Add cookie on request header (for authenticated web app).
String cookieContent = getCookieFromAppCookieManager(source.getHost());
request.addRequestHeader("Cookie", cookieContent);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
request.allowScanningByMediaScanner();
request.setNotificationVisibility(
android.app.DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
}
// Save the file in the "Downloads" folder of SDCARD.
request.setDestinationInExternalPublicDir(
android.os.Environment.DIRECTORY_DOWNLOADS, filename);
// Get the download service and enqueue the file.
android.app.DownloadManager manager =
(android.app.DownloadManager) this.currentActivity.getApplication()
.getSystemService(android.content.Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
public String getFilename(String contentDisposition){
String filename[] = contentDisposition.split("filename=");
return filename[1].replace("filename=", "").replace("\"", "").trim();
};
public String getCookieFromAppCookieManager(String url){
android.webkit.CookieManager cookieManager = android.webkit.CookieManager.getInstance();
if (cookieManager == null) {
return null;
}
String rawCookieHeader = null;
// Extract Set-Cookie header value from Android app CookieManager for this URL
rawCookieHeader = cookieManager.getCookie(url);
if (rawCookieHeader == null) {
return null;
}
return rawCookieHeader;
};
public void setCurrentActivity(MainActivity currentActivity) {
this.currentActivity = currentActivity;
}
}
当我单击 Web View 中的链接时,会出现此 java 错误:
java.lang.IllegalArgumentException: Can only download HTTP/HTTPS URIs: blob:file%3A///f566c1cf-b0b2-4382-ba16-90bab359fcc5
at android.app.DownloadManager$Request.<init>(DownloadManager.java:429)
当我在 HTTP 服务器上托管我的页面时,我遇到了同样的错误,因此该错误似乎源于 blob: 部分。
我现在有什么选择?如何下载存储在对象 URL 中的数据?最终,我想下载一个更大的 blob (~50MB)。
我可以将数据传递给注入(inject)到 addJavascriptInterface 中的对象。 ,但我必须 base64 encode my blob并在 java 端解码(因为只能传递原语和简单类型)。通过 javascript 编码为 base64 会使 Chromium 崩溃 50MB blob(调用 readAsDataURL 时出现内存不足错误)。
我还能如何从 Web View 下载 50MB 的 blob?或者将 50MB 二进制数据从 javascript 传输到 Android java?
== 用例详情 ==
我正在使用 javascript 生成一个 50MB 的视频文件 blob,mime 类型为 video/x-ms-wmv。这一代完全是客户端。我确信该步骤有效,因为我可以通过 object URL 在桌面浏览器(以及普通的 Chrome 应用程序)上下载文件。 .然后我想以某种方式让用户将该文件存储在他/她的外部存储中(可能在 DCIM 或下载中)。
另外,我还想对音频 WAV 文件做同样的事情(比如生成铃声以存储在铃声中)。
最佳答案
大卫,我已经调查过了。你在这里有一个很好的挑战。问题是 DownloadListener 确实需要一个 URI(例如 http://server.com/file.pdf )。但是,用户单击的链接不会传递该格式的 URI。传递的 URL 表示附加到浏览器 DOM 的 blob。因此,该解决方案将无法按设计工作。
您可能还有其他选择。这取决于您如何为 blob 生成字节。您提到您正在使用 Javascript 执行此操作。如果是这样,我将完全跳过使用 Blob 和 URL.createObjectURL 并编写一个 Javascript/Native 接口(interface),它允许您将字节 block (例如,n 个 255 字节的数组)传输到 Java 代码。这将降低客户端的内存消耗。
我对如何创建接口(interface)有一个想法,但我首先需要了解如何为 blob 生成字节。如果您可以发布一个字节数组,我可以使用它来测试我的解决方案。告诉我。
关于android - 在 Lollipop Web View 中下载对象 URL?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31113160/
总的来说,我对ruby还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用
在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev
我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss
好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信
从给定URL下载文件并立即将其上传到AmazonS3的更直接的方法是什么(+将有关文件的一些信息保存到数据库中,例如名称、大小等)?现在,我既不使用Paperclip,也不使用Carrierwave。谢谢 最佳答案 简单明了:require'open-uri'require's3'amazon=S3::Service.new(access_key_id:'KEY',secret_access_key:'KEY')bucket=amazon.buckets.find('image_storage')url='http://www.ex
我正在编写一个小脚本来定位aws存储桶中的特定文件,并创建一个临时验证的url以发送给同事。(理想情况下,这将创建类似于在控制台上右键单击存储桶中的文件并复制链接地址的结果)。我研究过回形针,它似乎不符合这个标准,但我可能只是不知道它的全部功能。我尝试了以下方法:defauthenticated_url(file_name,bucket)AWS::S3::S3Object.url_for(file_name,bucket,:secure=>true,:expires=>20*60)end产生这种类型的结果:...-1.amazonaws.com/file_path/file.zip.A
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
我在Rails工作并有以下类(class):classPlayer当我运行时bundleexecrailsconsole然后尝试:a=Player.new("me",5.0,"UCLA")我回来了:=>#我不知道为什么Player对象不会在这里初始化。关于可能导致此问题的操作/解释的任何建议?谢谢,马里奥格 最佳答案 havenoideawhythePlayerobjectwouldn'tbeinitializedhere它没有初始化很简单,因为你还没有初始化它!您已经覆盖了ActiveRecord::Base初始化方法,但您没有调
我有一个服务模型/表及其注册表。在表单中,我几乎拥有服务的所有字段,但我想在验证服务对象之前自动设置其中一些值。示例:--服务Controller#创建Action:defcreate@service=Service.new@service_form=ServiceFormObject.new(@service)@service_form.validate(params[:service_form_object])and@service_form.saverespond_with(@service_form,location:admin_services_path)end在验证@ser
我正在使用Rails构建一个简单的聊天应用程序。当用户输入url时,我希望将其输出为html链接(即“url”)。我想知道在Ruby中是否有任何库或众所周知的方法可以做到这一点。如果没有,我有一些不错的正则表达式示例代码可以使用... 最佳答案 查看auto_linkRails提供的辅助方法。这会将所有URL和电子邮件地址变成可点击的链接(htmlanchor标记)。这是文档中的代码示例。auto_link("Gotohttp://www.rubyonrails.organdsayhellotodavid@loudthinking.