View Full Version : Geting filename on a file upload
Dani
Sep 12th, 2007, 04:09 PM
Hi, I have a form that allows users to upload a file. It uses the commons multipart resolver, and I use a ByteArrayMultipartFileEditor to get the byte[] content.
But I'd also like to get the name of the file that has been sent (i.e: readme.txt). Is that possible?
Thanks .
sergi
Sep 12th, 2007, 06:42 PM
Sure, use MultipartHttpServletRequest (http://www.springframework.org/docs/api/org/springframework/web/multipart/MultipartHttpServletRequest.html) for this. Then you will be able to get the content of the file and some information as the one you ask for.
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
MultipartFile mf = multipartRequest.getFile("file");
byte [] fileBytes = mf.getBytes(); // File content
String name = mf.getOriginalFilename(); //File name
long size = mf.getSize(); //File size
Sergi Almar
DavidHorton
Sep 13th, 2007, 08:36 PM
The best place to implement Sergi's suggestion (assuming you are also making use of Spring's validator hooks) is to override the onBind method within your form controller.
For example...
public class FileUploadController extends SimpleFormController {
...
/**
* Specify custom behaviour on binding to extract the filename from the file uploaded
* in the multipart request.
*/
protected void onBind(HttpServletRequest req, Object command, BindException errors) {
// Get the filename from the request.
FileUploadBean uplBean = (FileUploadBean) command;
MultipartHttpServletRequest multiReq = (MultipartHttpServletRequest) req;
MultipartFile multipart = multiReq.getFile("data");
uplBean.setFileName(multipart.getOriginalFilename( ));
}
The onBind method is called after the standard binding (when the file data and other request parameters are bound) but before any validators are called. The standard implementation is an empty implementation in BaseCommandController. Overriding this method will bind the additional info from the multipart request allowing you to validate it along with other parameters in any validators you have configured.
Dave
vBulletin® v3.7.3, Copyright ©2000-2008, Jelsoft Enterprises Ltd.