Implementing file upload and download functions in Java class libraries through the SimpleHttpServer framework
Implementing file upload and download functions in Java class libraries through the SimpleHttpServer framework
When developing web applications, file uploading and downloading are very common requirements. Java provides many class libraries to handle file operations, and by using the SimpleHttpServer framework, we can easily implement these functions.
SimpleHttpServer is a simple and easy-to-use Java HTTP server framework that helps us create our own HTTP servers to handle communication with web browsers. Below, we will demonstrate how to use SimpleHttpServer to implement file upload and download functions.
Firstly, we need to create a Java class to handle HTTP requests and responses. We can use the HttpHandler class provided by the SimpleHttpServer framework to achieve this functionality. Here is an example:
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import java.io.*;
import java.net.URLEncoder;
public class FileHandler implements HttpHandler {
private static final String UPLOAD_DIRECTORY = "upload";
@Override
public void handle(HttpExchange exchange) throws IOException {
String requestMethod = exchange.getRequestMethod();
if (requestMethod.equalsIgnoreCase("GET")) {
handleDownloadRequest(exchange);
} else if (requestMethod.equalsIgnoreCase("POST")) {
handleUploadRequest(exchange);
}
}
private void handleDownloadRequest(HttpExchange exchange) throws IOException {
String requestedFile = exchange.getRequestURI().getPath().substring(1);
File file = new File(UPLOAD_DIRECTORY + File.separator + requestedFile);
if (file.exists()) {
exchange.sendResponseHeaders(200, file.length());
OutputStream outputStream = exchange.getResponseBody();
FileInputStream fileInputStream = new FileInputStream(file);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fileInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
fileInputStream.close();
outputStream.close();
} else {
String response = "File not found: " + requestedFile;
exchange.sendResponseHeaders(404, response.length());
OutputStream outputStream = exchange.getResponseBody();
outputStream.write(response.getBytes());
outputStream.close();
}
}
private void handleUploadRequest(HttpExchange exchange) throws IOException {
String boundary = exchange.getRequestHeaders().getFirst("Content-Type").split("=")[1];
InputStream inputStream = exchange.getRequestBody();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("Content-Disposition: form-data")) {
String fileName = line.substring(line.lastIndexOf("=") + 2, line.lastIndexOf("\""));
if (!fileName.isEmpty()) {
File file = new File(UPLOAD_DIRECTORY + File.separator + fileName);
FileOutputStream fileOutputStream = new FileOutputStream(file);
while (!(line = bufferedReader.readLine()).equals("--" + boundary)) {
if (!line.equals("--" + boundary + "--")) {
fileOutputStream.write(line.getBytes());
fileOutputStream.write("\r
".getBytes());
}
}
fileOutputStream.close();
}
}
}
String response = "File uploaded successfully";
exchange.sendResponseHeaders(200, response.length());
OutputStream outputStream = exchange.getResponseBody();
outputStream.write(response.getBytes());
outputStream.close();
}
}
In the above code, we created a class called FileHandler to handle HTTP requests. The handle method calls the handleDownloadRequest method to process the download request, or the handleUploadRequest method to process the upload request, based on the type of method requested. In the handleDownloadRequest method, we first check if the file exists, and if so, write the file content to the response output stream. If the file does not exist, write an error message to the response output stream. In the handleUploadRequest method, we parse the request body to obtain the uploaded file name and create a new file to save the uploaded file content.
Next, we need to create a simple HTTP server and associate FileHandler with the request path. This can be easily achieved using the SimpleHttpServer framework. Here is an example:
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
public class Main {
public static void main(String[] args) {
try {
HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
server.createContext("/files", new FileHandler());
server.start();
System.out.println("Server started on port 8000");
} catch (IOException e) {
e.printStackTrace();
}
}
}
In the above code, we created an HTTP server and associated FileHandler with the path '/files'. This means that when the client issues an HTTP request through this path, the FileHandler will process the request in the future. We start the server on port 8000 and output the corresponding information on the console.
Now we can upload and download files by sending HTTP requests. For example, to upload a file, we can use the curl command:
curl --location --request POST 'http://localhost:8000/files' \
--header 'Content-Type: multipart/form-data; boundary=--------------------------1234567890' \
--form 'file=@/path/to/file.txt'
To download the file, we can use the curl command:
curl --location --request GET 'http://localhost:8000/files/file.txt' --output file.txt
By using the SimpleHttpServer framework, we can easily implement file upload and download functions in Java class libraries. I hope this article is helpful to you!