At Spring
public ModelAndView fileUpload(HttpServletRequest request, HttpServletResponse response)
throws Exception{
MultipartRequest multipartReq = (MultipartRequest)request;
MultipartFile multipartFile = multipartReq.getFile("multipartFile");
String savePath = getServletContext().getRealPath("/")+File.separator+"destDir";
if(multipartFile.isEmpty())
{
response.setHeader(UPLOAD_RESPONSE, "1");
response.setHeader(UPLOAD_DESC, "Empty File");
return null;
}
try
{
File dir = new File(savePath);
if(!dir.exists()) dir.mkdir();
String fileName = savePath + File.separator + multipartFile.getOriginalFilename();
multipartFile.transferTo(new File(fileName));
}catch(Exception e){
response.setHeader(UPLOAD_RESPONSE, "1");
response.setHeader(UPLOAD_DESC, e.getMessage());
return null;
}
response.setHeader(UPLOAD_RESPONSE, "0");
response.setHeader(UPLOAD_DESC, "Success");
return null;
}
At .. Normal Servlet
try{
ServletFileUpload upload = new ServletFileUpload();
FileItemIterator iter = upload.getItemIterator(request);
while (iter.hasNext()) {
FileItemStream item = iter.next();
String name = item.getFieldName();
System.out.println("fieldName : "+name);
InputStream stream = item.openStream();
if (item.isFormField()) {
System.out.println("Form field " + name + " with value "
+ Streams.asString(stream) + " detected.");
} else {
System.out.println("File field " + name + " with file name "
+ item.getName() + " detected.");
byte[] ar = new byte[1024];
String dir = "destDir";
System.out.println("item name : "+item.getName());
String fname = null;
if(item.getName().lastIndexOf("\\")+1 <= 0)
fname = item.getName().substring(item.getName().lastIndexOf("/")+1);
else
fname = item.getName().substring(item.getName().lastIndexOf("\\")+1);
if(new File(dir+fname).exists())
fname = dir+"_"+fname;
else
fname = dir+fname;
System.out.println("save as : "+fname);
FileOutputStream fout = new FileOutputStream(fname);
int read = 0;
for(;;){
read = stream.read(ar);
if(read < 0)
{
fout.close();
break;
}
fout.write(ar,0,read);
}
}
}
}catch(Exception e){
//handle exception
}