Wednesday 8 October 2008

[Spring] file upload example

you need two jar file library.

- commons-io-1.4.jar
- commons-fileupload-1.2.jar

=== HTML ====
[form method="post" action="uploadFile.htm" enctype="multipart/form-data"]
[input type="file" name="file1"/]
[input type="submit"/]
[/form]

============ dispatcher-servlet.xml ====================

[bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver"]
[property name="maxUploadSize" value="100000"/]
[property name="uploadTempDir" ref="uploadDirResource"/]
[/bean]

[bean id="uploadDirResource"
class="org.springframework.core.io.FileSystemResource"]
[constructor-arg]
[value]C:/test111[/value]
[/constructor-arg]
[/bean]


==================== Controller =====
@Override
protected ModelAndView onSubmit(HttpServletRequest request,
HttpServletResponse response, Object command, BindException errors)throws ServletException, IOException {


MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest)request;

MultipartFile filea = multipartRequest.getFile("file1");


InputStream inputStream = null;
OutputStream outputStream = null;
if (filea.getSize() > 0) {


inputStream = filea.getInputStream();
File realUpload = new File("C:/");
outputStream = new FileOutputStream("C:/test111/"+filea.getOriginalFilename());
System.out.println("====22=========");
System.out.println(filea.getOriginalFilename());
System.out.println("=============");
int readBytes = 0;
byte[] buffer = new byte[8192];
while ((readBytes = inputStream.read(buffer, 0 , 8192))!=-1){
System.out.println("===ddd=======");
outputStream.write(buffer, 0, readBytes);
}
outputStream.close();
inputStream.close();
}

return new ModelAndView("fileupload");
}

5 comments:

Excelf said...

The information is of great help thanks!

Dario said...

This example is really useful indeed! just a question...
what the line
"File realUpload = new File("C:/");"
is used for? it seems that the variable "realUpload" is not used anywhere..

Anonymous said...

HI Thank you for the example.
Your code works perfectly for any file. However I had a specific requirement about reading Japanese file line by line. Here is what I modified to work with Japanese file. Note: UTF-8 did not work for me.

buff = new BufferedReader(new InputStreamReader(inputStream,"ISO-8859-1"));
buffWrite = new BufferedWriter(new OutputStreamWriter(outputStream,"ISO-8859-1"));
String line = "";
while((line = buff.readLine())!=null)
{
buffWrite.write(line);
}

GreenT

Anonymous said...

its good but it is a basic model we cant use this in spring

gethea said...

navigate herego to this website click siteread what he said have a peek at these guyssee this website