I'm creating an API for my application. In the GUI browser based application the file is uploaded via a form submission. So I simply do CommonsMultipartFile file = request.getFile(myfile)
. However, the API will provide an absolute path to the file as a string rather than uploading the file. My application will have access to this absolute path.
So that I don't have to change the underlying methods of my application (which accept the common interface MultiPartFile
For API purposes, I would like to read the file from this absolute path and create a CommonsMultipartFile
object which can be passed around to the methods that I am already using for GUI browser based application.
How can I do this? Constructor to CommonsMultipartFile
accepts a FileItem
This is API-specific code. i.e. not the usual file upload code.
Usual steps would be to:
This answer replaces 2 & 3 with logic independent of servlets - it avoids using ServletFileUpload (servlet-specific) and its ancestor FileUpload (so as to control the file location with an absolute path name). Note: (3) usually examines HTTP request parameters to determine lower-level parameters that are passed to FileItemFactory.createItem - these parameters are instead provided manually, and then only used as informational metadata. Replacement for 2 & 3:
Requested code provided below. At the end it invokes common code - shared with Servlet upload.
// Initialise Apache Commons FileItemFactory for API use only
FileItemFactory fif = new DiskFileItemFactory(sizeThreshold, repositoryBaseDirFile);
// Create Apache Commons FileItem & write file at fullFilePathString into it
FileItem fi = fif.createItem(fieldName, contentType, isFormField, fileName);
fi.write(new java.io.File(new java.net.URI(fullFilePathString));
// Convert FileItem to Spring wrapper: CommonsMultipartFile
org.springframework.web.multipart.MultipartFile mf = new CommonsMultipartFile(fi);
// From here, reuse the same code as the servlet upload. Operate only upon
// Spring MultipartFile, but not ServletFileUpload, FileItemFactory etc...
Parameters:
(Because ServletFileUpload & FileUpload are avoided, the following become metadata fields only, and are not used to control processing)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With