Handling File Uploads and PDF Viewing in Flutter WebView

Flutter

Flutter’s WebView is powerful, but some common browser features like file uploads and PDF rendering require a little extra work. In this article, we’ll walk through how to handle file uploads and PDF viewing inside a Flutter WebView app.

1. File Uploads in WebView

By default, the webview_flutter package does not support file inputs (<input type="file">). To support file uploads, you’ll need to use a platform-specific implementation or switch to a more advanced plugin like flutter_inappwebview.

Using flutter_inappwebview

Add the package to your pubspec.yaml:

dependencies:
  flutter_inappwebview: ^6.0.0

Then, use InAppWebView with file upload enabled:

import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

class WebViewFileUpload extends StatefulWidget {
  @override
  _WebViewFileUploadState createState() => _WebViewFileUploadState();
}

class _WebViewFileUploadState extends State<WebViewFileUpload> {
  late InAppWebViewController _webViewController;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("WebView File Upload")),
      body: InAppWebView(
        initialUrlRequest: URLRequest(
          url: Uri.parse("https://your-website-with-file-upload.com"),
        ),
        onWebViewCreated: (controller) {
          _webViewController = controller;
        },
        androidOnShowFileChooser: (controller, fileChooserParams) async {
          // Optional: Customize the file picker here
          return null; // Let the system picker handle it
        },
      ),
    );
  }
}

2. Viewing PDFs in WebView

Most mobile browsers do not render PDF files natively inside WebView. Instead, you can:

  • Embed the PDF using Google Docs Viewer or PDF.js
  • Use a dedicated PDF viewer plugin for better performance

Option A: Google Docs Viewer

https://docs.google.com/gview?embedded=true&url=YOUR_PDF_URL

Wrap this URL in your WebView:

webViewController.loadUrl(
  urlRequest: URLRequest(
    url: Uri.parse("https://docs.google.com/gview?embedded=true&url=https://example.com/sample.pdf"),
  ),
);

Option B: Dedicated PDF Plugin

If you need full control over PDFs, consider using packages like:

  • flutter_pdfview
  • syncfusion_flutter_pdfviewer

Conclusion

While Flutter’s default WebView lacks support for file uploads and PDFs, with the right packages and workarounds, you can provide a fully-featured browser experience in your app. For file uploads, flutter_inappwebview is your best bet. For PDFs, try Google Docs Viewer for simplicity or a dedicated viewer for performance.

Comment

Copied title and URL