我正在尝试连接ContentResolver和Firebase Storage下载。
目标:将文件从Firebase存储下载到图片库或音频文件夹中。
我做了什么:
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, "FileName1");
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.RELATIVE_PATH, "Pictures" + customDir);
AsyncQueryHandler asyncQueryHandler1 = new AsyncQueryHandler(myContentResolver){
@Override
protected void onInsertComplete(int token, Object cookie, Uri uri) {
super.onInsertComplete(token, cookie, uri);
File localFile = new File(uri.getPath());
StorageReference ref = FirebaseStorage.getInstance().getReference(myFireStorageFilePath());
ref.getFile(localFile).addOnSuccessListener(new OnSuccessListener<FileDownloadTask.TaskSnapshot>() {
........
}
};
asyncQueryHandler1.startInsert(-1, null, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
但是,我得到了错误(即使我请求了权限):
E/StorageException: Permission denied
java.io.IOException: Permission denied
at java.io.UnixFileSystem.createFileExclusively0(Native Method)
at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:317)
at java.io.File.createNewFile(File.java:1008)
at com.google.firebase.storage.FileDownloadTask.processResponse(com.google.firebase:firebase-storage@@17.0.0:138)
at com.google.firebase.storage.FileDownloadTask.run(com.google.firebase:firebase-storage@@17.0.0:229)
at com.google.firebase.storage.StorageTask.lambda$getRunnable$7(com.google.firebase:firebase-storage@@17.0.0:1106)
at com.google.firebase.storage.StorageTask$$Lambda$10.run(Unknown Source:2)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
at java.lang.Thread.run(Thread.java:919)
我不明白自己在做什么错。我可以创建Uri然后创建文件吗?
谢谢
答案 0 :(得分:0)
最终我无法在API> = 29中将Uri和File粘在一起,但这对我有用:
# Import the basic modules to run this script
import ssl
from datetime import datetime
import OpenSSL
import socket
from datetime import timedelta
import datetime
import traceback
import logging
# Import the needed libs for sending smtp emails
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.base import MIMEBase
from email import encoders
# Set variables for email
email_sen = 'sen@email.com'
email_rec = 'rec@email.com'
subject = 'SSL Certificate Results'
# Create message container for email
msg = MIMEMultipart('alternative')
msg['From'] = email_sen
msg['To'] = email_rec
msg['Subject'] = subject
# Setup logging
logger = logging.getLogger(__name__)
logger.setLevel(logging.WARNING)
formatter = logging.Formatter('%(asctime)s:%(levelname)s:%(message)s')
file_handler = logging.FileHandler('log/SSLNag.log')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
try:
# opening file with list of servers and set date and time
ipfile = open('server_ip.txt')
cur_date = datetime.datetime.utcnow()
# Create an array to house the results.
# Array will have sub arrays in the format of [host ip] = {host, hostname, expiration date, days to expire}
ssl_results = {}
except Exception as e:
logger.warning("ERROR ENCOUNTERED! \n\n")
logger.warning(str(traceback.format_exc()))
# scan each host in the ip file and check it's ssl
for ip in ipfile:
# Record an entry in the ssl_resutls array
# Always default to false
ssl_results[str(ip)] = {'host': '', 'server_name': '', 'exp_date': '', 'days_to_expire': ''}
try:
host = ip.strip().split(':')[0]
port = ip.strip().split(':')[1]
print('\nChecking certifcate for server ', host)
# Connect to server using SSL.
ctx = OpenSSL.SSL.Context(ssl.PROTOCOL_TLSv1)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host, int(port)))
cnx = OpenSSL.SSL.Connection(ctx, s)
cnx.set_connect_state()
cnx.do_handshake()
# Connection complete get SSL certificate and close connection.
cert = cnx.get_peer_certificate()
s.close()
# From SSL certificate get host name, expiration date and decode.
server_name = cert.get_subject().commonName
print(server_name)
edate = cert.get_notAfter()
edate = edate.decode()
# Get date and format. Calculate number of days until SSL expires.
exp_date = datetime.datetime.strptime(edate, '%Y%m%d%H%M%SZ')
days_to_expire = int((exp_date - cur_date).days)
print(exp_date)
print('day to expire', days_to_expire)
# Update the hosts entry
ssl_results[str(ip)]['host'] = host
ssl_results[str(ip)]['server_name'] = server_name
ssl_results[str(ip)]['exp_date'] = exp_date
ssl_results[str(ip)]['days_to_expire'] = days_to_expire
# Logging for errors
except Exception as e:
logger.warning('Error on connection to Server,', str(ip))
logger.warning("ERROR ENCOUNTERED", host, "\n\n")
logger.warning(str(traceback.format_exc()))
# Loop through the ssl_results entries and generate a email + results file
try:
# Sort the ssl_results
sorted_results = sorted(ssl_results.items(),
key=lambda k: k[1]['days_to_expire'], reverse=False)
# variable to hold html for email
SSLCertificates = """<html>
<head>
<style>
table{width: 1024px;}
table, th, td {
border: 1px solid black;
border-collapse: collapse;
}
th, td {
padding: 5px;
text-align: left;
}
ul:before{
content:attr(data-header);
font-size:120%;
font-weight:bold;
margin-left:-15px;
}
</style>
</head>
<body>
<p><h2>Hello, </h2>
<h3>SSL Expiration Summary:</h3>
<span style="color:red;"><b>NOTE: If any of the below SSL certificates have less than 90 days remaining please renew.<b></span><br><br>
<table id=\"exp_ssls\"><tr><th>Host</th><th>Hostname</th><th>Expiration Date</th><th>Remaining Days</th></tr>
"""
# Write results in an html table
# Apply this formatting if days to expire are equal to or less than 90 days
for server, data in sorted_results:
if float(str(data["days_to_expire"])) <= 90:
SSLCertificates += "<tr><td bgcolor=yellow><font color=red><b>" + str(server) + "</b></td><td bgcolor=yellow><font color=red><b>" + str(data["server_name"]) + "</b></td><td bgcolor=yellow><font color=red><b>" + str(
data["exp_date"]) + "</b></td><td bgcolor=yellow><font color=red><b>" + str(data["days_to_expire"]) + "</b></td></tr>"
# Apply this formatting if days to expire are equal to or greater than 91 days
if float(str(data["days_to_expire"])) >= 91:
SSLCertificates += "<tr><td>" + str(server) + "</td><td>" + str(data["server_name"]) + "</td><td>" + str(
data["exp_date"]) + "</td><td>" + str(data["days_to_expire"]) + "</td></tr>"
SSLCertificates += """</body>
</html>"""
# Write data to a file and attach it to the email
f = open('SSLCertificates.html', 'w')
f.write(SSLCertificates)
f.close()
filename = 'SSLCertificates.html'
attachment = open(filename, 'rb')
# Setup email attachment
msg.attach(MIMEText(SSLCertificates, 'html'))
part = MIMEBase('application', 'octet-stream')
part.set_payload(attachment.read())
encoders.encode_base64(part)
part.add_header('Content-Disposition', "attachment; filename=" + filename)
# Send email
msg.attach(part)
text = msg.as_string()
server = smtplib.SMTP('smtp.server.com', 25)
server.sendmail(email_sen, email_rec, text)
server.quit()
# Logging for errors
except Exception as e:
logging.warning("ERROR ENCOUNTERED! \n\n")
logging.warning(str(traceback.format_exc()))
功能:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
values = new ContentValues();
values.put(MediaStore.MediaColumns.DISPLAY_NAME, af.getFileName());
values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
values.put(MediaStore.MediaColumns.RELATIVE_PATH, "Pictures" + customDir);
values.put(MediaStore.MediaColumns.IS_PENDING, 1);
AsyncQueryHandler asyncQueryHandler1 = new AsyncQueryHandler(cr){
@Override
protected void onInsertComplete(int token, Object cookie, Uri uri) {
super.onInsertComplete(token, cookie, uri);
onUriCreated(uri, af, token, fr);
}
};
asyncQueryHandler1.startInsert(i, null, MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
}
文件保存位置:
void onUriCreated(Uri uri, Attachedfile af, int finalI, FileRepo fr) {
if(uri != null){
StorageReference ref = FirebaseStorage.getInstance().getReference(myFireStorageFilePath);
ref.getDownloadUrl().addOnSuccessListener(new OnSuccessListener<Uri>() {
@Override
public void onSuccess(Uri downloadUri) {
RetrieveAndInsert(downloadUri.toString(), uri, finalI, af, fr);
}
}).addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception exception) {
// Handle any errors
}
});
}
}