Created
October 7, 2016 03:01
-
-
Save devheedoo/83cc17a391639fc3515a0d8f6dbe9ae2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
File Upload | |
on Spring project | |
*/ | |
/* | |
<form> in jsp need enctype attribute. For example: | |
<form name="formA" id="formA" method="post" enctype="multipart/form-data" action="[your_address]"> | |
... | |
</form> | |
*/ | |
if (ServletFileUpload.isMultipartContent(request)) { | |
ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory()); | |
// UTF-8 Encoding | |
uploadHandler.setHeaderEncoding("UTF-8"); | |
List<FileItem> items = uploadHandler.parseRequest(request); | |
// For each files | |
for (FileItem item : items) { | |
// If there's file | |
if (item.getSize() > 0) { | |
// Get default file path | |
String defaultPath = request.getSession().getServletContext().getRealPath("/"); | |
// Get detail file path | |
String path = defaultPath + "/upload/category1/"; | |
// On local server, path might be: | |
// C:\workspace\[your_workspace_name]\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\[your_project_name]\/upload/category1/ | |
// If no directory, make it | |
File folder = new File(path); | |
if (!folder.exists()) { | |
folder.mkdirs(); | |
} | |
// Get extension name | |
String ext = item.getName().substring(item.getName().lastIndexOf(".") + 1); | |
// Make a new filename for upload using UUID | |
String realname = UUID.randomUUID().toString() + "." + ext; | |
///////////////// Write a file on server ///////////////// | |
InputStream is = item.getInputStream(); | |
OutputStream os = new FileOutputStream(path + realname); | |
int numRead; | |
byte b[] = new byte[(int) item.getSize()]; | |
while ((numRead = is.read(b, 0, b.length)) != -1) { | |
os.write(b, 0, numRead); | |
} | |
if (is != null) is.close(); | |
os.flush(); | |
os.close(); | |
///////////////// End ///////////////// | |
} else { | |
// No files to upload | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment