import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.math.BigInteger; import java.security.SecureRandom; import java.util.Iterator; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.apache.commons.io.FilenameUtils; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import com.google.gson.JsonObject; public class ImageUpload extends HttpServlet { private static final long serialVersionUID = 1L; private Logger logger = null; private File tmpDir; private static final String DESTINATION_DIR_PATH ="/images/new"; private static final String TEMP_DIR_PATH ="/images/temp"; private File destinationDir; public ImageUpload() { super(); logger = LogManager.getLogger(ImageUpload.class); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //do nothing here ... } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { tmpDir = new File(TEMP_DIR_PATH); if(!tmpDir.isDirectory()) { throw new ServletException(TEMP_DIR_PATH + " is not a directory"); } destinationDir = new File(DESTINATION_DIR_PATH); if(!destinationDir.isDirectory()) { destinationDir.mkdirs(); } //PrintWriter to send the JSON response back PrintWriter out = response.getWriter(); //set content type and header attributes response.setContentType("text/html"); response.setHeader("Cache-control", "no-cache, no-store"); response.setHeader("Pragma", "no-cache"); response.setHeader("Expires", "-1"); response.setHeader("Access-Control-Allow-Origin", "*"); response.setHeader("Access-Control-Allow-Methods", "POST"); response.setHeader("Access-Control-Allow-Headers", "Content-Type"); response.setHeader("Access-Control-Max-Age", "86400"); DiskFileItemFactory fileItemFactory = new DiskFileItemFactory (); //Set the size threshold, above which content will be stored on disk. fileItemFactory.setSizeThreshold(1*1024*1024); //1 MB //Set the temporary directory to store the uploaded files of size above threshold. fileItemFactory.setRepository(tmpDir); ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory); JsonObject myObj = new JsonObject(); File file = null; String filename = null; try { //Parse the request List items = uploadHandler.parseRequest(request); Iterator iterator = items.iterator(); while(iterator.hasNext()) { FileItem item = (FileItem) iterator.next(); //Handle Form Fields if(item.isFormField()) { if(item.getFieldName().trim().equalsIgnoreCase("pictureDirectory")){ String pictureDirectory = item.getString().trim(); if(pictureDirectory.trim().equals("")){ pictureDirectory = DESTINATION_DIR_PATH; destinationDir = new File(DESTINATION_DIR_PATH); if(!destinationDir.isDirectory()) { destinationDir.mkdirs(); } } } logger.debug("File Name = "+item.getFieldName()+", Value = "+item.getString()); } //Handle Uploaded files. else { logger.debug("Field Name = " + item.getFieldName()+ ", File Name = " + item.getName()+ ", Content type = " + item.getContentType()+ ", File Size = " + item.getSize()); //Write file to the ultimate location. filename = item.getName().trim(); file = new File(destinationDir, filename); item.write(file); //Write the file with a new name filename = getRandomString() + "." + FilenameUtils.getExtension(filename); file = new File(destinationDir, filename); item.write(file); } } myObj.addProperty("success", true); myObj.addProperty("picturePath", file.getAbsolutePath()); myObj.addProperty("pictureName", filename); logger.debug("End..."); } catch(FileUploadException ex) { ex.printStackTrace(); myObj.addProperty("success", false); } catch(Exception ex) { ex.printStackTrace(); myObj.addProperty("success", false); out.println(myObj.toString()); } out.println(myObj.toString()); out.close(); } private String getRandomString() { SecureRandom random = new SecureRandom(); String randomString = new BigInteger(130, random).toString(32); return(randomString); } }
All one can think and do in a short time is to think what one already knows and to do as one has always done!
No comments:
Post a Comment
NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.