Java upload file to servlet without using html form

Yes, you can upload a file to a servlet in Java without using an HTML form. Here's an example using the Apache HttpClient library:

  1. Add the Apache HttpClient library to your project by adding the following dependency to your pom.xml file:
refer ‮‬to:theitroad.com
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.13</version>
</dependency>
  1. In your client code, create an instance of the HttpClient class and a HttpPost request:
String url = "http://localhost:8080/myapp/upload";
HttpClient httpclient = HttpClients.createDefault();
HttpPost httppost = new HttpPost(url);
  1. Create a FileBody object for the file you want to upload:
File file = new File("/path/to/file.txt");
FileBody fileBody = new FileBody(file);
  1. Create an instance of the MultipartEntityBuilder class and add the FileBody object to it:
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addPart("file", fileBody);
HttpEntity entity = builder.build();
httppost.setEntity(entity);
  1. Execute the HttpPost request:
HttpResponse response = httpclient.execute(httppost);
  1. In your servlet code, use the HttpServletRequest object to retrieve the uploaded file:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    Part filePart = request.getPart("file");
    String fileName = filePart.getSubmittedFileName();
    InputStream fileContent = filePart.getInputStream();
    // process the uploaded file
}

In this example, the HttpPost request sends a multipart/form-data message with a FileBody part to the servlet. The servlet uses the HttpServletRequest object to retrieve the uploaded file and its metadata.

Note that this example does not handle errors or exceptions. You should add appropriate error handling to your code.