Upload files (pdf/image) using our upload api

Copy this link and integrate in your app/website for file upload.

https://innovhub.in/tools/api/upload.php

Backend Code Implementation

Python Code


# Python PDF Upload Example (e.g., for a Tkinter/PyQt/PySide desktop app or CLI)

import requests
import json
import os # For path manipulation and file existence checks

def upload_pdf_file(local_pdf_file_path):
    """
    Uploads a PDF file to the specified PHP API endpoint.

    Args:
        local_pdf_file_path (str): The full path to the local PDF file.
    """
    # --- 1. Define the API endpoint URL ---
    # IMPORTANT: Replace with the actual URL of your upload.php script
    upload_api_url = "http://innovhub.in/upload.php"  # Example URL

    # Check if the local PDF file exists
    if not os.path.exists(local_pdf_file_path):
        print(f"Error: PDF file not found at: {local_pdf_file_path}")
        # In a GUI app, you'd use a message box here, e.g.:
        # messagebox.showerror("Error", f"PDF file not found at: {local_pdf_file_path}")
        return

    print(f"Uploading PDF from: {local_pdf_file_path} to {upload_api_url}...")
    # In a GUI app, update a status label here.

    try:
        # Open the PDF file in binary read mode
        with open(local_pdf_file_path, 'rb') as f:
            # Prepare the files dictionary for requests.post
            # The key 'innovhub' MUST match the name expected by your PHP script ($_FILES["innovhub"]).
            # The value is a tuple: (filename, file_object, content_type)
            files = {
                'innovhub': (os.path.basename(local_pdf_file_path), f, 'application/pdf')
            }

            # Send the POST request
            response = requests.post(upload_api_url, files=files)

            # Raise an exception for bad status codes (4xx or 5xx)
            response.raise_for_status()

            # Parse the JSON response
            json_response = response.json()

            # Check the 'status' field from the JSON response
            if json_response.get("status") == "success":
                file_url = json_response.get("file_url")
                print(f"PDF uploaded successfully! URL: {file_url}")
                # In a GUI app, use a message box:
                # messagebox.showinfo("Success", f"PDF uploaded successfully! URL: {file_url}")
                return file_url # Return the URL for further use
            else:
                error_message = json_response.get("message", "Unknown error from server.")
                print(f"Error: PDF upload failed: {error_message}")
                # In a GUI app, use a message box:
                # messagebox.showerror("Upload Error", f"PDF upload failed: {error_message}")
                return None

    except requests.exceptions.RequestException as e:
        # Handle network or HTTP specific errors
        print(f"Network or server error: {e}")
        # messagebox.showerror("Connection Error", f"Network or server error: {e}")
        return None
    except json.JSONDecodeError as e:
        # Handle JSON parsing errors
        print(f"Error parsing server response (not valid JSON): {e}")
        print(f"Server response body: {response.text}")
        # messagebox.showerror("Response Error", f"Error parsing server response: {e}")
        return None
    except Exception as e:
        # Handle other general errors
        print(f"An unexpected error occurred: {e}")
        # messagebox.showerror("Error", f"An unexpected error occurred: {e}")
        return None
    finally:
        # In a GUI app, reset status label here.
        print("Upload process finished.")


# --- Example Usage ---
if __name__ == "__main__":
    # Replace with the actual path to your dynamically generated PDF
    test_pdf_path = "C:\\Temp\\Invoice_ClientXYZ.pdf"

    # Create a dummy PDF file for testing if it doesn't exist
    if not os.path.exists(test_pdf_path):
        try:
            with open(test_pdf_path, 'w') as f:
                f.write("This is a dummy PDF content for testing.")
            print(f"Created dummy PDF for testing: {test_pdf_path}")
        except IOError as e:
            print(f"Failed to create dummy PDF: {e}")

    uploaded_url = upload_pdf_file(test_pdf_path)
    if uploaded_url:
        print(f"Successfully uploaded. Public URL: {uploaded_url}")
    else:
        print("PDF upload failed.")

    # In a Tkinter/PyQt app, you would call upload_pdf_file from a button click handler
    # For example:
    # from tkinter import Tk, Button, Label, filedialog
    #
    # def select_and_upload():
    #     file_path = filedialog.askopenfilename(filetypes=[("PDF files", "*.pdf")])
    #     if file_path:
    #         upload_pdf_file(file_path)
    #
    # root = Tk()
    # root.title("PDF Uploader")
    #
    # upload_button = Button(root, text="Upload PDF", command=select_and_upload)
    # upload_button.pack(pady=20)
    #
    # status_label = Label(root, text="Ready")
    # status_label.pack()
    #
    # root.mainloop()


/*
This example uses the popular requests library, which simplifies HTTP requests significantly. You'll need to install it.
pip install requests

Python Notes:

requests: This is the de-facto standard for HTTP requests in Python. It's very user-friendly.
files parameter: The requests library handles the multipart/form-data encoding automatically when you pass a dictionary to the files parameter. The key ('innovhub') is the form field name, and the value is a tuple containing the filename, the file object (opened in binary mode rb), and optionally the content type.
response.raise_for_status(): A convenient method to automatically raise an HTTPError for 4xx or 5xx responses.
response.json(): Parses the JSON response directly into a Python dictionary.
Error Handling: Uses try...except blocks to catch various types of errors, including network issues (requests.exceptions.RequestException) and JSON parsing problems (json.JSONDecodeError).
*/
                    

DotNet Code


                    // C# PDF Upload Example (e.g., in a Windows Forms or WPF application)

                    using System;
                    using System.IO;
                    using System.Net.Http;
                    using System.Net.Http.Headers;
                    using System.Text.Json; // For JSON parsing
                    using System.Threading.Tasks;
                    using System.Windows.Forms; // For MessageBox in WinForms, adjust for WPF/other UI
                    
                    public class PdfUploader
                    {
                        // Asynchronous method to upload a PDF file
                        public static async Task UploadPdfFile(string localPdfFilePath)
                        {
                            // --- 1. Define the API endpoint URL ---
                            // IMPORTANT: Replace with the actual URL of your upload.php script
                            string uploadApiUrl = "http://yourdomain.com/upload.php"; // Example URL
                    
                            // Check if the local PDF file exists
                            if (!File.Exists(localPdfFilePath))
                            {
                                MessageBox.Show($"PDF file not found at: {localPdfFilePath}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }
                    
                            // You might want to update a UI element (e.g., a Label or ProgressBar) here
                            // to indicate that the upload is in progress.
                            // Example: someStatusLabel.Text = "Uploading PDF...";
                    
                            try
                            {
                                // Create a new HttpClient instance
                                using (HttpClient client = new HttpClient())
                                {
                                    // Create a new MultipartFormDataContent to hold the file data
                                    using (MultipartFormDataContent formData = new MultipartFormDataContent())
                                    {
                                        // Read the PDF file into a byte array
                                        byte[] fileBytes = File.ReadAllBytes(localPdfFilePath);
                    
                                        // Create a ByteArrayContent from the file bytes
                                        using (ByteArrayContent fileContent = new ByteArrayContent(fileBytes))
                                        {
                                            // Set the Content-Type header for the file.
                                            // For PDF, it's application/pdf. For images, it would be image/jpeg, image/png, etc.
                                            fileContent.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
                    
                                            // Add the file content to the form data.
                                            // The first parameter "innovhub" MUST match the name expected by your PHP script ($_FILES["innovhub"]).
                                            // The second parameter is the filename that will be sent to the server.
                                            formData.Add(fileContent, "innovhub", Path.GetFileName(localPdfFilePath));
                    
                                            // Send the POST request asynchronously
                                            HttpResponseMessage response = await client.PostAsync(uploadApiUrl, formData);
                    
                                            // Ensure the HTTP response was successful (status code 200-299)
                                            response.EnsureSuccessStatusCode();
                    
                                            // Read the response content as a string (which should be JSON)
                                            string responseBody = await response.Content.ReadAsStringAsync();
                    
                                            // Parse the JSON response using System.Text.Json
                                            JsonDocument jsonDoc = JsonDocument.Parse(responseBody);
                                            JsonElement root = jsonDoc.RootElement;
                    
                                            // Check the 'status' field from the JSON response
                                            if (root.TryGetProperty("status", out JsonElement statusElement) && statusElement.GetString() == "success")
                                            {
                                                string fileUrl = root.GetProperty("file_url").GetString();
                                                MessageBox.Show($"PDF uploaded successfully! URL: {fileUrl}", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                                // You can now use 'fileUrl' in your application, e.g., save it to a database
                                                Console.WriteLine($"Uploaded PDF URL: {fileUrl}");
                                            }
                                            else
                                            {
                                                string errorMessage = root.GetProperty("message").GetString();
                                                MessageBox.Show($"PDF upload failed: {errorMessage}", "Upload Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                                Console.WriteLine($"Upload Error: {errorMessage}");
                                            }
                                        }
                                    }
                                }
                            }
                            catch (HttpRequestException ex)
                            {
                                // Handle HTTP specific errors (e.g., network issues, server not found)
                                MessageBox.Show($"Network or server error: {ex.Message}", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                Console.WriteLine($"HttpRequestException: {ex.Message}");
                            }
                            catch (Exception ex)
                            {
                                // Handle other general errors (e.g., JSON parsing errors, file access errors)
                                MessageBox.Show($"An unexpected error occurred: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                Console.WriteLine($"General Exception: {ex.Message}");
                            }
                            finally
                            {
                                // Reset UI status here, e.g.:
                                // someStatusLabel.Text = "Ready";
                            }
                        }
                    
                        // Example usage in a Windows Forms application:
                        /*
                        private async void MyUploadButton_Click(object sender, EventArgs e)
                        {
                            string pdfPath = "C:\\Temp\\Invoice_ClientXYZ.pdf"; // Your dynamic PDF path
                            await UploadPdfFile(pdfPath);
                        }
                        */
                    }
                    
                    
                    /*
                    C# Notes:
                    
                    1. System.Text.Json: This is the recommended JSON library for new .NET projects (.NET Core 3.1+ / .NET 5+). If you're using an older .NET Framework version, you might need to install Newtonsoft.Json (Json.NET) via NuGet and use JObject.Parse as shown in the VB.NET example.
                    2. Asynchronous: The async/await pattern keeps your UI responsive during the upload.
                    3. MessageBox: Used for simple UI feedback. In a real application, you'd use a more sophisticated way to display messages (e.g., a status bar, custom dialogs).
                    */
                    

Java Code


// Java PDF Upload Example (e.g., in a Swing or JavaFX application)

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.util.concurrent.CompletableFuture; // For asynchronous operations
import javax.swing.JOptionPane; // For simple UI feedback in Swing

// For JSON parsing, you'll need a library like org.json or Jackson.
// Example uses org.json:
import org.json.JSONObject;

public class PdfUploader {

    // Method to upload a PDF file
    public static void uploadPdfFile(String localPdfFilePath) {
        // --- 1. Define the API endpoint URL ---
        // IMPORTANT: Replace with the actual URL of your upload.php script
        String uploadApiUrl = "http://innovhub.in/tools/api/upload.php"; // Example URL

        File pdfFile = new File(localPdfFilePath);

        // Check if the local PDF file exists
        if (!pdfFile.exists() || !pdfFile.isFile()) {
            JOptionPane.showMessageDialog(null, "PDF file not found at: " + localPdfFilePath, "Error", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // You might want to update a UI element (e.g., a JLabel or ProgressBar) here
        // to indicate that the upload is in progress.
        // Example: statusLabel.setText("Uploading PDF...");

        HttpClient client = HttpClient.newHttpClient();

        try {
            // Read the PDF file into a byte array
            byte[] fileBytes = Files.readAllBytes(pdfFile.toPath());

            // Define the boundary for multipart/form-data
            String boundary = "---" + System.currentTimeMillis();
            HttpRequest.Builder requestBuilder = HttpRequest.newBuilder()
                    .uri(URI.create(uploadApiUrl))
                    .header("Content-Type", "multipart/form-data; boundary=" + boundary);

            // Build the request body for multipart/form-data
            // The "innovhub" name must match what PHP expects ($_FILES["innovhub"])
            // The filename for the server is the original file's name.
            HttpRequest.BodyPublisher bodyPublisher = HttpRequest.BodyPublishers.ofByteArray(
                buildMultipartBody(fileBytes, "innovhub", pdfFile.getName(), "application/pdf", boundary)
            );

            HttpRequest request = requestBuilder.POST(bodyPublisher).build();

            // Send the request asynchronously to avoid blocking the UI thread
            CompletableFuture> futureResponse = client.sendAsync(request, HttpResponse.BodyHandlers.ofString());

            // Handle the response when it's ready
            futureResponse.thenAccept(response -> {
                if (response.statusCode() >= 200 && response.statusCode() < 300) {
                    // Successful HTTP status code
                    String responseBody = response.body();
                    try {
                        JSONObject jsonResponse = new JSONObject(responseBody);

                        if ("success".equals(jsonResponse.getString("status"))) {
                            String fileUrl = jsonResponse.getString("file_url");
                            JOptionPane.showMessageDialog(null, "PDF uploaded successfully! URL: " + fileUrl, "Success", JOptionPane.INFORMATION_MESSAGE);
                            System.out.println("Uploaded PDF URL: " + fileUrl);
                        } else {
                            String errorMessage = jsonResponse.getString("message");
                            JOptionPane.showMessageDialog(null, "PDF upload failed: " + errorMessage, "Upload Error", JOptionPane.ERROR_MESSAGE);
                            System.err.println("Upload Error: " + errorMessage);
                        }
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(null, "Error parsing server response: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                        System.err.println("JSON parsing error: " + e.getMessage());
                    }
                } else {
                    // Handle HTTP error status codes
                    JOptionPane.showMessageDialog(null, "Server responded with status: " + response.statusCode() + "\n" + response.body(), "HTTP Error", JOptionPane.ERROR_MESSAGE);
                    System.err.println("HTTP Error: " + response.statusCode() + " - " + response.body());
                }
                // Reset UI status here, e.g.:
                // statusLabel.setText("Ready");
            }).exceptionally(ex -> {
                // Handle network or other exceptions during the request
                JOptionPane.showMessageDialog(null, "An error occurred during upload: " + ex.getMessage(), "Connection Error", JOptionPane.ERROR_MESSAGE);
                System.err.println("Exception during HTTP request: " + ex.getMessage());
                // Reset UI status here, e.g.:
                // statusLabel.setText("Ready");
                return null;
            });

        } catch (IOException e) {
            JOptionPane.showMessageDialog(null, "Error reading PDF file: " + e.getMessage(), "File Error", JOptionPane.ERROR_MESSAGE);
            System.err.println("IOException reading file: " + e.getMessage());
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, "An unexpected error occurred: " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
            System.err.println("General Exception: " + e.getMessage());
        }
    }

    // Helper method to build the multipart/form-data body
    private static byte[] buildMultipartBody(byte[] fileBytes, String fieldName, String fileName, String contentType, String boundary) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);

        // Part for the file
        writer.append("--").append(boundary).append("\r\n");
        writer.append("Content-Disposition: form-data; name=\"").append(fieldName).append("\"; filename=\"").append(fileName).append("\"\r\n");
        writer.append("Content-Type: ").append(contentType).append("\r\n");
        writer.append("Content-Transfer-Encoding: binary\r\n");
        writer.append("\r\n").flush();
        outputStream.write(fileBytes);
        outputStream.flush();
        writer.append("\r\n").flush();

        // End of multipart/form-data
        writer.append("--").append(boundary).append("--").append("\r\n").flush();

        return outputStream.toByteArray();
    }

    // Example usage in a main method or a button click handler for a Swing app:
    public static void main(String[] args) {
        // This would typically be triggered by a button click in a GUI application
        // For demonstration purposes:
        String pdfPath = "C:\\Temp\\SampleInvoice.pdf"; // Replace with your actual PDF path

        // Create a dummy PDF file for testing if it doesn't exist
        if (!new File(pdfPath).exists()) {
            try {
                Files.write(new File(pdfPath).toPath(), "This is a dummy PDF content.".getBytes());
                System.out.println("Created dummy PDF for testing: " + pdfPath);
            } catch (IOException e) {
                System.err.println("Failed to create dummy PDF: " + e.getMessage());
            }
        }

        uploadPdfFile(pdfPath);
    }
}

/*
This example uses java.net.http.HttpClient (available from Java 11 onwards) for HTTP requests and org.json for JSON parsing. You'll need to add org.json to your project's dependencies (e.g., Maven, Gradle, or manually add the JAR).

Maven Dependency for org.json:

    <dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20240303</version>
    </dependency>


Java Notes:

Java 11+ HttpClient: This is a modern, built-in HTTP client. If you need to support older Java versions (e.g., Java 8), you'd typically use HttpURLConnection or a third-party library like Apache HttpClient.
org.json: A simple JSON library. For more robust JSON handling (especially for complex objects), consider Jackson or Gson.
CompletableFuture: Used for asynchronous operations to prevent the UI from freezing.
buildMultipartBody: A helper method is needed to manually construct the multipart/form-data request body, as HttpClient doesn't have a direct utility for this like .NET's MultipartFormDataContent.
*/