i have an website that has users. Credentials read from an sql database each user sees his folder with his vat i have a folder structure and i want could download files from there from browser works perfect but from webview not. After a lot attempts i make it to start the download in the download manager but stops immediately. trys again but nothing here is how folder structure works and how download url works in app.js
// Route to get the folder structure
app.get('/get-folder-structure', async (req, res) => {
if (!req.session.vat) {
return res.status(401).json({ error: 'Unauthorized' });
}
const vat = req.session.vat.toString();
const folderPath = path.join('D:', vat);
try {
const folderStructure = await getFolderStructure(folderPath);
res.json(folderStructure);
} catch (error) {
console.error('Error reading folder structure:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
});
// Route to download a file
app.get('/download/:filePath', (req, res) => {
// Decode the file path
const decodedPath = decodeURIComponent(req.params.filePath);
// Construct the full path
const fullPath = path.join('D:\', decodedPath);
// Log the full path
console.log('Attempting to access file at:', fullPath);
// Check if the file exists and has read permissions
fs.access(fullPath, fs.constants.R_OK, (err) => {
if (err) {
console.error('File not found or access error:', err);
res.status(404).json({ error: 'File not found' });
} else {
res.download(fullPath, (downloadErr) => {
if (downloadErr) {
console.error('Error during file download:', downloadErr);
res.status(500).json({ error: 'Error during file download' });
}
});
}
});
});
i want could download from webview too like from browsers i try scoped storage i try with and without permission bu nothing. here will find how i try to download without success what you suggest?
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Request permissions
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE
}, REQUEST_CODE_PERMISSIONS);
}
// Initialize the WebView
myWeb = findViewById(R.id.myWeb);
myWeb.getSettings().setJavaScriptEnabled(true); // Enable JavaScript
myWeb.getSettings().setAllowFileAccess(true); // Allow file access for uploads
myWeb.getSettings().setDomStorageEnabled(true); // Enable DOM storage
myWeb.getSettings().setMediaPlaybackRequiresUserGesture(false); // Allow media playback without user gesture
// Handle SSL errors
myWeb.setWebViewClient(new WebViewClient() {
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
handler.proceed(); // Ignore SSL certificate errors
}
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String url = request.getUrl().toString();
if (url.endsWith(".pdf") || url.endsWith(".zip") || url.endsWith(".jpg") || url.endsWith(".png") ||
url.endsWith(".xlsx") || url.endsWith(".xls") || url.endsWith(".docx") || url.endsWith(".txt") || url.endsWith(".doc") || url.endsWith(".html")) {
// Handle specific file types if needed
// For now, just return null to let WebView handle it
return null;
}
return super.shouldInterceptRequest(view, request);
}
});
// Handle permission requests for the camera and other resources
myWeb.setWebChromeClient(new WebChromeClient() {
@Override
public void onPermissionRequest(final PermissionRequest request) {
request.grant(request.getResources());
}
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
mFilePathCallback = filePathCallback;
Intent intent = fileChooserParams.createIntent();
try {
startActivityForResult(intent, FILE_CHOOSER_REQUEST_CODE);
} catch (ActivityNotFoundException e) {
mFilePathCallback.onReceiveValue(null);
}
return true;
}
});
myWeb.setDownloadListener(new DownloadListener() {
@Override
public void onDownloadStart(String url, String userAgent, String contentDisposition, String mimetype, long contentLength) {
startDownload(url, userAgent, contentDisposition, mimetype);
}
});
// Enable WebView debugging
WebView.setWebContentsDebuggingEnabled(true);
// Load the desired URL
myWeb.loadUrl("https://***.***.***.***:***/");
}
private void startDownload(String url, String userAgent, String contentDisposition, String mimetype) {
// Create a DownloadManager request
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));
request.setMimeType(mimetype);
request.addRequestHeader("User-Agent", userAgent);
request.setDescription("Downloading file...");
request.setTitle(URLUtil.guessFileName(url, contentDisposition, mimetype));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, URLUtil.guessFileName(url, contentDisposition, mimetype));
// Enqueue the download
DownloadManager downloadManager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
downloadManager.enqueue(request);
Toast.makeText(getApplicationContext(), "Downloading File...", Toast.LENGTH_SHORT).show();
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == REQUEST_CODE_PERMISSIONS) {
boolean allPermissionsGranted = true;
for (int result : grantResults) {
if (result != PackageManager.PERMISSION_GRANTED) {
allPermissionsGranted = false;
break;
}
}
if (allPermissionsGranted) {
Toast.makeText(this, "Permissions granted. You can now download files.", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "Permissions are required to download files.", Toast.LENGTH_SHORT).show();
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == FILE_CHOOSER_REQUEST_CODE) {
if (mFilePathCallback == null) return;
Uri[] results = null;
if (resultCode == RESULT_OK) {
if (data != null) {
results = WebChromeClient.FileChooserParams.parseResult(resultCode, data);
}
}
mFilePathCallback.onReceiveValue(results);
mFilePathCallback = null;
}
}
}