Below are examples of a basic file upload functionality for both images and PDF files in C#, Java, and Golang. In these examples, I’ll assume a simple console-based application, and in a real-world scenario, you would integrate this with a web application and handle file uploads through a web form.
C# Image and PDF File Upload:
using System; using System.IO; class Program { static void Main() { Console.WriteLine("Enter file path (image or PDF):"); string filePath = Console.ReadLine(); if (File.Exists(filePath)) { string fileType = Path.GetExtension(filePath).ToLower(); if (fileType == ".jpg" || fileType == ".png" || fileType == ".pdf") { Console.WriteLine("File uploaded successfully in C#."); } else { Console.WriteLine("Invalid file type. Only JPG, PNG, and PDF are allowed."); } } else { Console.WriteLine("File not found."); } } }
Java Image and PDF File Upload:
import java.util.Scanner; import java.io.File; public class FileUploadExample { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); System.out.println("Enter file path (image or PDF):"); String filePath = scanner.nextLine(); File file = new File(filePath); if (file.exists()) { String fileType = getFileExtension(file); if (fileType.equals("jpg") || fileType.equals("png") || fileType.equals("pdf")) { System.out.println("File uploaded successfully in Java."); } else { System.out.println("Invalid file type. Only JPG, PNG, and PDF are allowed."); } } else { System.out.println("File not found."); } } static String getFileExtension(File file) { String name = file.getName(); int lastIndexOfDot = name.lastIndexOf("."); return (lastIndexOfDot == -1) ? "" : name.substring(lastIndexOfDot + 1); } }
Golang (Go) Image and PDF File Upload:
package main import ( "fmt" "path/filepath" ) func main() { fmt.Println("Enter file path (image or PDF):") var filePath string fmt.Scanln(&filePath) if fileExists(filePath) { fileType := getFileExtension(filePath) if fileType == "jpg" || fileType == "png" || fileType == "pdf" { fmt.Println("File uploaded successfully in Golang.") } else { fmt.Println("Invalid file type. Only JPG, PNG, and PDF are allowed.") } } else { fmt.Println("File not found.") } } func fileExists(filePath string) bool { _, err := filepath.Abs(filePath) return err == nil } func getFileExtension(filePath string) string { ext := filepath.Ext(filePath) return ext[1:] }
These examples demonstrate a basic file upload check for images (JPG and PNG) and PDF files in C#, Java, and Golang. In a web application, you would typically handle file uploads through a form, validate file types, and store them securely. Ensure that you handle user-uploaded files with caution to prevent security vulnerabilities.