Antonis
Antonis

Reputation: 1061

Simulate a multiple file upload with one file

Hi to all I have a sample code using Jakarta HttpClient that uploads a file to a web server. What i want is to simulate a multiple file upload of the same file with different name for each upload. Is this possible? Any hints?

A.K.

Upvotes: 2

Views: 1560

Answers (1)

BalusC
BalusC

Reputation: 1108632

Just add different multipart parts with same file content but a different part and filename. With InputStreamBody you can specify a different filename for each part. E.g.

MultipartEntity entity = new MultipartEntity();
entity.addPart("file1", new InputStreamBody(new FileInputStream(file), "name1.ext"));
entity.addPart("file2", new InputStreamBody(new FileInputStream(file), "name2.ext"));
entity.addPart("file3", new InputStreamBody(new FileInputStream(file), "name3.ext"));
// ...

In the Servlet code, assuming that you're using Commons FileUpload, you could just iterate over the multipart items which you've extracted from the request with help of the FileUpload API in a for loop.

List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
    if (item.isFormField()) {
        // Process regular field.
    } else {
        // Process uploaded file.
    }
}

Upvotes: 3

Related Questions