Java Code Examples for org.springframework.web.multipart.MultipartHttpServletRequest#getFileNames()

The following examples show how to use org.springframework.web.multipart.MultipartHttpServletRequest#getFileNames() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
private void doTestMultipartHttpServletRequest(MultipartHttpServletRequest request) throws IOException {
	Set<String> fileNames = new HashSet<>();
	Iterator<String> fileIter = request.getFileNames();
	while (fileIter.hasNext()) {
		fileNames.add(fileIter.next());
	}
	assertEquals(2, fileNames.size());
	assertTrue(fileNames.contains("file1"));
	assertTrue(fileNames.contains("file2"));
	MultipartFile file1 = request.getFile("file1");
	MultipartFile file2 = request.getFile("file2");
	Map<String, MultipartFile> fileMap = request.getFileMap();
	List<String> fileMapKeys = new LinkedList<>(fileMap.keySet());
	assertEquals(2, fileMapKeys.size());
	assertEquals(file1, fileMap.get("file1"));
	assertEquals(file2, fileMap.get("file2"));

	assertEquals("file1", file1.getName());
	assertEquals("", file1.getOriginalFilename());
	assertNull(file1.getContentType());
	assertTrue(ObjectUtils.nullSafeEquals("myContent1".getBytes(), file1.getBytes()));
	assertTrue(ObjectUtils.nullSafeEquals("myContent1".getBytes(),
		FileCopyUtils.copyToByteArray(file1.getInputStream())));
	assertEquals("file2", file2.getName());
	assertEquals("myOrigFilename", file2.getOriginalFilename());
	assertEquals("text/plain", file2.getContentType());
	assertTrue(ObjectUtils.nullSafeEquals("myContent2".getBytes(), file2.getBytes()));
	assertTrue(ObjectUtils.nullSafeEquals("myContent2".getBytes(),
		FileCopyUtils.copyToByteArray(file2.getInputStream())));
}
 
Example 2
@RequestMapping(value = "upload", method = RequestMethod.POST)
public @ResponseBody ResponseEntity<UploadFileContainer> upload(MultipartHttpServletRequest request,
        HttpServletResponse response) {

    if (path == null) {
        logger.error("Path must be not null");
        return new ResponseEntity<UploadFileContainer>(HttpStatus.INTERNAL_SERVER_ERROR);
    }

    LinkedList<FileMeta> files = new LinkedList<FileMeta>();
    MultipartFile mpf = null;

    for (Iterator<String> it = request.getFileNames(); it.hasNext();) {
        mpf = request.getFile(it.next());
        logger.debug("{} uploaded", mpf.getOriginalFilename());

        FileMeta fileContainer = new FileMeta();
        fileContainer.setName(mpf.getOriginalFilename());
        fileContainer.setSize(mpf.getSize() / 1024 + "Kb");
        fileContainer.setFileType(mpf.getContentType());

        try {
            fileContainer.setBytes(mpf.getBytes());
            createFolderIfNotExists();
            FileCopyUtils.copy(mpf.getBytes(),
                    new BufferedOutputStream(new FileOutputStream(path + mpf.getOriginalFilename())));
            // the copy method closed the output stream
        } catch (IOException e) {
            logger.error("Error during file upload", e);
            fileContainer.setError(e.getMessage());
        }
        files.add(fileContainer);
    }

    UploadFileContainer uploadFileContainer = new UploadFileContainer(files);
    return new ResponseEntity<UploadFileContainer>(uploadFileContainer, HttpStatus.OK);
}
 
Example 3
Source Project: WeEvent   File: FileService.java    License: Apache License 2.0 5 votes vote down vote up
private UploadChunkParam parseUploadChunkRequest(HttpServletRequest request) throws GovernanceException {
    UploadChunkParam chunkParam = new UploadChunkParam();
    String fileId = request.getParameter("identifier");
    FileChunksMeta fileChunksMeta = this.fileChunksMap.get(fileId).getKey();

    chunkParam.setFileChunksMeta(fileChunksMeta);
    chunkParam.setBrokerId(Integer.parseInt(request.getParameter("brokerId")));
    chunkParam.setChunkNumber(Integer.parseInt(request.getParameter("chunkNumber")) - 1);
    chunkParam.setFileId(fileId);

    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
    if (multipartResolver.isMultipart(request)) {
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
            MultipartFile file = multiRequest.getFile(iter.next());
            if (!Objects.isNull(file)) {
                try {
                    chunkParam.setChunkData(file.getBytes());
                } catch (IOException e) {
                    log.error("parse upload chunk data error.", e);
                    throw new GovernanceException(ErrorCode.PARSE_CHUNK_REQUEST_ERROR);
                }
            }
        }
    }
    return chunkParam;
}
 
Example 4
private void doTestMultipartHttpServletRequest(MultipartHttpServletRequest request) throws IOException {
	Set<String> fileNames = new HashSet<>();
	Iterator<String> fileIter = request.getFileNames();
	while (fileIter.hasNext()) {
		fileNames.add(fileIter.next());
	}
	assertEquals(2, fileNames.size());
	assertTrue(fileNames.contains("file1"));
	assertTrue(fileNames.contains("file2"));
	MultipartFile file1 = request.getFile("file1");
	MultipartFile file2 = request.getFile("file2");
	Map<String, MultipartFile> fileMap = request.getFileMap();
	List<String> fileMapKeys = new LinkedList<>(fileMap.keySet());
	assertEquals(2, fileMapKeys.size());
	assertEquals(file1, fileMap.get("file1"));
	assertEquals(file2, fileMap.get("file2"));

	assertEquals("file1", file1.getName());
	assertEquals("", file1.getOriginalFilename());
	assertNull(file1.getContentType());
	assertTrue(ObjectUtils.nullSafeEquals("myContent1".getBytes(), file1.getBytes()));
	assertTrue(ObjectUtils.nullSafeEquals("myContent1".getBytes(),
		FileCopyUtils.copyToByteArray(file1.getInputStream())));
	assertEquals("file2", file2.getName());
	assertEquals("myOrigFilename", file2.getOriginalFilename());
	assertEquals("text/plain", file2.getContentType());
	assertTrue(ObjectUtils.nullSafeEquals("myContent2".getBytes(), file2.getBytes()));
	assertTrue(ObjectUtils.nullSafeEquals("myContent2".getBytes(),
		FileCopyUtils.copyToByteArray(file2.getInputStream())));
}
 
Example 5
Source Project: sdb-mall   File: WxMaMediaController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 上传临时素材
 *
 * @return 素材的media_id列表,实际上如果有的话,只会有一个
 */
@PostMapping("/upload")
public List<String> uploadMedia(HttpServletRequest request) throws WxErrorException {
    CommonsMultipartResolver resolver = new CommonsMultipartResolver(request.getSession().getServletContext());

    if (!resolver.isMultipart(request)) {
        return Lists.newArrayList();
    }

    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    Iterator<String> it = multiRequest.getFileNames();
    List<String> result = Lists.newArrayList();
    while (it.hasNext()) {
        try {
            MultipartFile file = multiRequest.getFile(it.next());
            File newFile = new File(Files.createTempDir(), file.getOriginalFilename());
            this.logger.info("filePath is :" + newFile.toString());
            file.transferTo(newFile);
            WxMediaUploadResult uploadResult = this.service.getMediaService().uploadMedia(WxMaConstants.KefuMsgType.IMAGE, newFile);
            this.logger.info("media_id : " + uploadResult.getMediaId());
            result.add(uploadResult.getMediaId());
        } catch (IOException e) {
            this.logger.error(e.getMessage(), e);
        }
    }

    return result;
}
 
Example 6
private void doTestMultipartHttpServletRequest(MultipartHttpServletRequest request) throws IOException {
	Set<String> fileNames = new HashSet<String>();
	Iterator<String> fileIter = request.getFileNames();
	while (fileIter.hasNext()) {
		fileNames.add(fileIter.next());
	}
	assertEquals(2, fileNames.size());
	assertTrue(fileNames.contains("file1"));
	assertTrue(fileNames.contains("file2"));
	MultipartFile file1 = request.getFile("file1");
	MultipartFile file2 = request.getFile("file2");
	Map<String, MultipartFile> fileMap = request.getFileMap();
	List<String> fileMapKeys = new LinkedList<String>(fileMap.keySet());
	assertEquals(2, fileMapKeys.size());
	assertEquals(file1, fileMap.get("file1"));
	assertEquals(file2, fileMap.get("file2"));

	assertEquals("file1", file1.getName());
	assertEquals("", file1.getOriginalFilename());
	assertNull(file1.getContentType());
	assertTrue(ObjectUtils.nullSafeEquals("myContent1".getBytes(), file1.getBytes()));
	assertTrue(ObjectUtils.nullSafeEquals("myContent1".getBytes(),
		FileCopyUtils.copyToByteArray(file1.getInputStream())));
	assertEquals("file2", file2.getName());
	assertEquals("myOrigFilename", file2.getOriginalFilename());
	assertEquals("text/plain", file2.getContentType());
	assertTrue(ObjectUtils.nullSafeEquals("myContent2".getBytes(), file2.getBytes()));
	assertTrue(ObjectUtils.nullSafeEquals("myContent2".getBytes(),
		FileCopyUtils.copyToByteArray(file2.getInputStream())));
}
 
Example 7
Source Project: jeewx   File: QywxNewsitemController.java    License: Apache License 2.0 5 votes vote down vote up
/**
   * 上传文件信息
   * @param request
   * @param response
   * @return
   */
  @RequestMapping(params = "doUpload", method = RequestMethod.POST)
  @ResponseBody
  public  AjaxJson doUpload(MultipartHttpServletRequest request, HttpServletResponse response) {
  	AjaxJson j = new AjaxJson();
Map<String, Object> attributes = new HashMap<String, Object>();
try {
	String basePath = request.getSession().getServletContext().getRealPath("/");
	//获取所有文件名称  
	Iterator<String> it = request.getFileNames();  
	while(it.hasNext()){  
	    //根据文件名称取文件  
	    MultipartFile multifile = request.getFile(it.next());  
	    String fileName = multifile.getOriginalFilename(); 
	    String filePath = "upload/files/"; 
	    File file = new File(basePath+filePath);
		if (!file.exists()) {
			file.mkdir();// 创建文件根目录
		}
		filePath = filePath+fileName;
	    String savePath = basePath+filePath;
	    System.out.println(savePath);
	    File newFile = new File(savePath);  
	    //上传的文件写入到指定的文件中  
	    multifile.transferTo(newFile);  
	    attributes.put("url", filePath);
	    attributes.put("fileKey", fileName);
	}
	j.setMsg("文件上传成功");
	j.setAttributes(attributes);
}  catch (Exception e) {
	e.printStackTrace();
	j.setSuccess(false);
	j.setMsg("文件上传失败");
}  

return j;
  }
 
Example 8
Source Project: mumu   File: DocUploadController.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 上传文件
 * @param request
 * @return
 */
public File uploadFile(HttpServletRequest request) {
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
    try {
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            Iterator<String> iterator = multiRequest.getFileNames();
            while (iterator.hasNext()) {
                String key = iterator.next();
                MultipartFile multipartFile = multiRequest.getFile(key);
                if (multipartFile != null) {
                    String name = multipartFile.getOriginalFilename();
                    String pathDir = request.getSession().getServletContext().getRealPath("/upload/" + DateUtils.currentTime());
                    File dirFile = new File(pathDir);
                    if (!dirFile.isDirectory()) {
                        dirFile.mkdirs();
                    }
                    String filePath = pathDir+File.separator+name;
                    File file = new File(filePath);
                    file.setWritable(true, false);

                    multipartFile.transferTo(file);
                    return file;
                }
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}
 
Example 9
Source Project: mumu   File: UploadUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
    * 上传文件处理(支持批量)
    * @param request
    * @param pathDir 上传文件保存路径
    * @return
    * @throws IllegalStateException
    * @throws IOException
    */
public static List<String> uploadFile(HttpServletRequest request,String pathDir) throws IllegalStateException, IOException {
	CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
			request.getSession().getServletContext());
	List<String> fileNames = InstanceUtil.newArrayList();
	if (multipartResolver.isMultipart(request)) {
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Iterator<String> iterator = multiRequest.getFileNames();
		if(pathDir==null|| pathDir.equals("")){
			pathDir = request.getSession().getServletContext().getRealPath(uploadFileDir + DateUtils.currentTime());
		}
           File dirFile = new File(pathDir);
           if (!dirFile.isDirectory()) {
               dirFile.mkdirs();
           }
		while (iterator.hasNext()) {
			String key = iterator.next();
			MultipartFile multipartFile = multiRequest.getFile(key);
			if (multipartFile != null) {
				String uuid = UUID.randomUUID().toString().replace("-", "");
				String name = multipartFile.getOriginalFilename();
				int lastIndexOf = name.lastIndexOf(".");
				String postFix="";
				if(lastIndexOf!=-1){
					postFix = name.substring(lastIndexOf).toLowerCase();
				}
				String fileName = uuid + postFix;
				String filePath = pathDir + File.separator + fileName;
				File file = new File(filePath);
				file.setWritable(true, false);

				multipartFile.transferTo(file);
				fileNames.add(file.getAbsolutePath());
			}
		}
	}
	return fileNames;
}
 
Example 10
Source Project: jcalaBlog   File: FileTools.java    License: MIT License 5 votes vote down vote up
/**
 * 从HttpServletRequest中获取MultipartFile
 */
private static MultipartFile getMultipartFile(HttpServletRequest request) {
    MultipartHttpServletRequest multipartRequest =
            (MultipartHttpServletRequest) request;
    Iterator<String> fileNames = multipartRequest.getFileNames();
    return multipartRequest.getFile(fileNames.next());
}
 
Example 11
/**
 * 上传图文封面图
 * @param request
 * @param response
 * @return
 */
@RequestMapping(params = "doUpload", method = RequestMethod.POST)
@ResponseBody
public  AjaxJson doUpload(MultipartHttpServletRequest request, HttpServletResponse response) {
	AjaxJson j = new AjaxJson();
	Map<String, Object> attributes = new HashMap<String, Object>();
	try {
		//String basePath = request.getSession().getServletContext().getRealPath("/");
		//String basePath = upLoadPath;
		//获取所有文件名称
		Iterator<String> it = request.getFileNames();  
		while(it.hasNext()){  
		    //根据文件名称取文件  
		    MultipartFile multifile = request.getFile(it.next());  
		    //author:sunkai--date:2018-10-10--for:上传图片时更换图片名---
		    //String realFilename=multifile.getOriginalFilename();
	        //String fileExtension = realFilename.substring(realFilename.lastIndexOf("."));
	        //String fileName=UUID.randomUUID().toString().replace("-", "")+fileExtension;
	        //author:sunkai--date:2018-10-10--for:上传图片时更换图片名---
		    //String filePath = "/upload/files/";
		    //File file = new File(basePath+filePath.replace("/", "\\"));
			//if (!file.exists()) {
			//	file.mkdirs();// 创建文件根目录
			//}
			//filePath = filePath+fileName;
		    //String savePath = basePath+filePath;
		    //File newFile = new File(savePath);
		    //上传的文件写入到指定的文件中
			String filename = OSSBootUtil.upload(multifile , "upload/files");
			attributes.put("url", filename);
			String format = filename .substring(filename .lastIndexOf("/") + 1);
			attributes.put("fileKey", format);
		}
		j.setMsg("文件上传成功");
		j.setAttributes(attributes);
	}  catch (Exception e) {
		e.printStackTrace();
		j.setSuccess(false);
		j.setMsg("文件上传失败");
	}  

	return j;
}
 
Example 12
/**
     * 파일을 Upload 처리한다. (이미지 전용)
     *
     * @param request
     * @param where
     * @param maxFileSize
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static List<HeritFormBasedFileVO> uploadExtensionFiles(HttpServletRequest request, String where, long maxFileSize) throws Exception {
		List<HeritFormBasedFileVO> list = new ArrayList<HeritFormBasedFileVO>();

		MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request;
		Iterator fileIter = mptRequest.getFileNames();

		while (fileIter.hasNext()) {
		    MultipartFile mFile = mptRequest.getFile((String)fileIter.next());

		    //LGU+ 보안 취약점 모듈 적용 (img 파일인지 점검)
		    if(SecurityModule.VulnerabilityChek(mFile.getOriginalFilename(), 0, "common", "fileup_img").equals("true")){
			    HeritFormBasedFileVO vo = new HeritFormBasedFileVO();

			    String tmp = mFile.getOriginalFilename();


			    String fileExtension = "";

		            if (tmp.lastIndexOf("\\") >= 0) {
		            	tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
		            }
		            if (tmp.lastIndexOf(".") >= 0) {
		            	fileExtension = tmp.substring(tmp.lastIndexOf(".") + 1);
		            }

		            vo.setFieldName(mFile.getName());
		            vo.setFileName(tmp);
		            vo.setContentType(mFile.getContentType());
		            //vo.setServerSubPath(getTodayString());
		            vo.setPhysicalName(getPhysicalFileName()+"."+fileExtension);
		            vo.setSize(mFile.getSize());

//		            if (tmp.lastIndexOf(".") >= 0) {
//		       	 	vo.setPhysicalName(vo.getPhysicalName());	// 2012.11 KISA 보안조치
//		            }

		            if (mFile.getSize() > 0) {
		            	InputStream is = null;

		            	try {
		            		is = mFile.getInputStream();
		            		//saveFile(is, new File(HeritWebUtil.filePathBlackList(where+SEPERATOR+vo.getServerSubPath()+SEPERATOR+vo.getPhysicalName())));
		            		saveFile(is, new File(HeritWebUtil.filePathBlackList(where+SEPERATOR+vo.getPhysicalName())));
		            	} finally {
		            		if (is != null) {
		            			is.close();
		            		}
		            	}
		            	list.add(vo);
		            }


		    }// LGU+ 보안 취약점 모듈 적용 (img 파일인지 점검) end


		}

		return list;
    }
 
Example 13
Source Project: mogu_blog_v2   File: CKImageUploadUtil.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 图片上传
 *
 * @param request
 * @param DirectoryName 文件上传目录:比如upload(无需带前面的/) upload/news ..
 * @return
 * @throws IllegalStateException
 * @throws IOException
 * @Title upload
 */
public static String upload(HttpServletRequest request, String DirectoryName) throws IllegalStateException,
        IOException {
    // 创建一个通用的多部分解析器
    CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession()
            .getServletContext());
    // 图片名称
    String fileName = null;
    // 判断 request 是否有文件上传,即多部分请求
    if (multipartResolver.isMultipart(request)) {
        // 转换成多部分request
        MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
        // 取得request中的所有文件名
        Iterator<String> iter = multiRequest.getFileNames();
        while (iter.hasNext()) {
            // 记录上传过程起始时的时间,用来计算上传时间
            // int pre = (int) System.currentTimeMillis();
            // 取得上传文件
            MultipartFile file = multiRequest.getFile(iter.next());
            if (file != null) {
                // 取得当前上传文件的文件名称
                String myFileName = file.getOriginalFilename();
                // 如果名称不为“”,说明该文件存在,否则说明该文件不存在
                if (myFileName.trim() != "") {
                    // 获得图片的原始名称
                    String originalFilename = file.getOriginalFilename();
                    // 获得图片后缀名称,如果后缀不为图片格式,则不上传
                    String suffix = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
                    if (!fileTypes.contains(suffix)) {
                        continue;
                    }
                    // 获得上传路径的绝对路径地址(/upload)-->
                    String realPath = basePath + DirectoryName;
                    System.out.println(realPath);
                    // 如果路径不存在,则创建该路径
                    File realPathDirectory = new File(realPath);
                    if (realPathDirectory == null || !realPathDirectory.exists()) {
                        realPathDirectory.mkdirs();
                    }
                    // 重命名上传后的文件名 111112323.jpg
                    fileName = UUID.randomUUID() + suffix;
                    // 定义上传路径 .../upload/111112323.jpg
                    File uploadFile = new File(realPathDirectory + "\\" + fileName);
                    System.out.println(uploadFile);
                    file.transferTo(uploadFile);
                }
            }
            // 记录上传该文件后的时间
            // int finaltime = (int) System.currentTimeMillis();
            // System.out.println(finaltime - pre);
        }
    }
    return fileName;
}
 
Example 14
/**
 * {@inheritDoc}
 */
@Override
public ModelAndView addFileUploadLine(final UifFormBase form) {
    form.setAjaxReturnType(UifConstants.AjaxReturnTypes.UPDATECOMPONENT.getKey());
    form.setAjaxRequest(true);

    MultipartHttpServletRequest request = (MultipartHttpServletRequest) form.getRequest();

    final String collectionId = request.getParameter(UifParameters.UPDATE_COMPONENT_ID);
    final String bindingPath = request.getParameter(UifConstants.PostMetadata.BINDING_PATH);

    Class<?> collectionObjectClass = (Class<?>) form.getViewPostMetadata().getComponentPostData(collectionId,
            UifConstants.PostMetadata.COLL_OBJECT_CLASS);

    Iterator<String> fileNamesItr = request.getFileNames();

    while (fileNamesItr.hasNext()) {
        String propertyPath = fileNamesItr.next();

        MultipartFile uploadedFile = request.getFile(propertyPath);

        final FileMeta fileObject = (FileMeta) KRADUtils.createNewObjectFromClass(collectionObjectClass);
        try {
            fileObject.init(uploadedFile);
        } catch (Exception e) {
            throw new RuntimeException("Unable to initialize new file object", e);
        }

        String id = UUID.randomUUID().toString() + "_" + uploadedFile.getName();
        fileObject.setId(id);

        fileObject.setDateUploaded(new Date());

        fileObject.setUrl("?methodToCall=getFileFromLine&formKey="
                + form.getFormKey()
                + "&fileName="
                + fileObject.getName()
                + "&propertyPath="
                + propertyPath);

        ViewLifecycle.encapsulateLifecycle(form.getView(), form, form.getViewPostMetadata(), null, request,
                new Runnable() {
                    @Override
                    public void run() {
                        ViewLifecycle.getHelper().processAndAddLineObject(form, fileObject, collectionId,
                                bindingPath);
                    }
                });
    }

    return getModelAndViewService().getModelAndView(form);
}
 
Example 15
/**
     * 파일을 Upload 처리한다.
     *
     * @param request
     * @param where
     * @param maxFileSize
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static List<HeritFormBasedFileVO> uploadFiles(HttpServletRequest request, String where, long maxFileSize) throws Exception {
    	List<HeritFormBasedFileVO> list = new ArrayList<HeritFormBasedFileVO>();

		MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request;
		Iterator fileIter = mptRequest.getFileNames();

		while (fileIter.hasNext()) {
		    MultipartFile mFile = mptRequest.getFile((String)fileIter.next());
		    HeritFormBasedFileVO vo = new HeritFormBasedFileVO();

		    String tmp = mFile.getOriginalFilename();

	            if (tmp.lastIndexOf("\\") >= 0) {
	        	tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
	            }

	            vo.setFieldName(mFile.getName());
	            vo.setFileName(tmp);
	            vo.setContentType(mFile.getContentType());
	            //서브디렉토리 주석처리
//	            vo.setServerSubPath(getTodayString());
	            vo.setPhysicalName(getPhysicalFileName());
	            vo.setSize(mFile.getSize());
	            //System.out.println("size : " + mFile.getSize());

	            if (tmp.lastIndexOf(".") >= 0) {
	       	 		vo.setPhysicalName(vo.getPhysicalName());	// 2012.11 KISA 보안조치
	            }

	            if (mFile.getSize() >= 0) {
	            	InputStream is = null;
	            	//System.out.println("size : " + mFile.getSize());
	            	try {
	            		is = mFile.getInputStream();
//	            		saveFile(is, new File(HeritWebUtil.filePathBlackList(where+SEPERATOR+vo.getServerSubPath()+SEPERATOR+vo.getPhysicalName())));
	            		saveFile(is, new File(HeritWebUtil.filePathBlackList(where+SEPERATOR+vo.getPhysicalName())));
	            		//System.out.println("saveFile Name : "+vo.getPhysicalName());
	            	} finally {
	            		if (is != null) {
	            			is.close();
	            		}
	            	}
	            	list.add(vo);
	            }
		}

		return list;
    }
 
Example 16
Source Project: lion   File: BaseController.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 文件上传(支持多个文件上传)
 *
 * @param request 请求对象
 */
protected List<String> fileUpload(HttpServletRequest request) {

    List<String> list = new ArrayList<>();

    // 转换成多部分request
    MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
    // 取得request中的所有文件名
    Iterator<String> iterator = multiRequest.getFileNames();
    while (iterator.hasNext()) {
        // 取得上传文件
        MultipartFile file = multiRequest.getFile(iterator.next());
        if (null != file) {
            // 获取当前上传文件的文件名称
            String originalFileName = file.getOriginalFilename();
            // 如果名称不为空说明该文件存在,否则说明该文件不存在
            if (!"".equals(originalFileName)) {
                long timestamp = DateUtil.getTimestamp();
                String currentDate = DateUtil.formatLocalDateTime(DateUtil.timestampToLocalDateTime(timestamp), "yyyy/MM/dd");
                // 获取文件后缀
                String fileSuffix = originalFileName.substring(originalFileName.lastIndexOf("."));
                // 重命名上传的文件名(格式:时间戳.后缀)
                String fileName = timestamp + fileSuffix;
                File dest = new File(fileUploadPath + "/upload/" + applicationName + "/" + currentDate, fileName);
                // 判断文件父目录是否存在
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                try {
                    // 保存文件成功后记录上传后的名称
                    file.transferTo(dest);
                    list.add(fileName);
                } catch (IOException e) {
                    throw new LionException(e.getMessage());
                }
            }
        }
    }

    return list.isEmpty() ? null : list;
}
 
Example 17
/**
     * HERE
     * @param request
     * @param where
     * @param maxFileSize
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static List<HeritFormBasedFileVO> filesUpload(HttpServletRequest request, String where, long maxFileSize) throws Exception {
    	List<HeritFormBasedFileVO> list = new ArrayList<HeritFormBasedFileVO>();

		MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request;
		Iterator fileIter = mptRequest.getFileNames();

		//System.out.println("in");
		
		while (fileIter.hasNext()) {
		    MultipartFile mFile = mptRequest.getFile((String)fileIter.next());
		    //if (mFile.getSize() == 0) {
		    //	continue;
		    //}
		    
		    HeritFormBasedFileVO vo = new HeritFormBasedFileVO();

		    String tmp = mFile.getOriginalFilename();
		    //System.out.println("Orifilename : "+tmp);
		    //System.out.println("filename : "+mFile.getName());
            if (tmp.lastIndexOf("\\") >= 0) {
            	tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
            }

            vo.setFieldName(mFile.getName());
            vo.setFileName(tmp);
            vo.setContentType(mFile.getContentType());
            //서브디렉토리 주석처리
//	            vo.setServerSubPath(getTodayString());
            vo.setPhysicalName(getPhysicalFileName());
            vo.setSize(mFile.getSize());
            //System.out.println("size : " + mFile.getSize());

            if (tmp.lastIndexOf(".") >= 0) {
       	 		vo.setPhysicalName(vo.getPhysicalName());	// 2012.11 KISA 보안조치
            }

            if (mFile.getSize() > 0) {
            	InputStream is = null;
            	//System.out.println("size : " + mFile.getSize());
            	try {
            		is = mFile.getInputStream();
//	            		saveFile(is, new File(HeritWebUtil.filePathBlackList(where+SEPERATOR+vo.getServerSubPath()+SEPERATOR+vo.getPhysicalName())));
            		
            		//저장되는 이름 제어
            		saveFile(is, new File(HeritWebUtil.filePathBlackList(where+SEPERATOR+vo.getFileName())));
            		//System.out.println("saveFile Name : "+vo.getFileName());
            	} catch(Exception e){
            		e.printStackTrace();
            	} finally {
            		if (is != null) {
            			is.close();
            		}
            	}
            }
        	list.add(vo);
		}

		return list;
    }
 
Example 18
/**
     * 파일을 Upload 처리한다. (이미지 전용)
     *
     * @param request
     * @param where
     * @param maxFileSize
     * @return
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public static List<HeritFormBasedFileVO> uploadExtensionFiles(HttpServletRequest request, String where, long maxFileSize) throws Exception {
		List<HeritFormBasedFileVO> list = new ArrayList<HeritFormBasedFileVO>();

		MultipartHttpServletRequest mptRequest = (MultipartHttpServletRequest)request;
		Iterator fileIter = mptRequest.getFileNames();

		while (fileIter.hasNext()) {
		    MultipartFile mFile = mptRequest.getFile((String)fileIter.next());

		    //LGU+ 보안 취약점 모듈 적용 (img 파일인지 점검)
		    if(SecurityModule.VulnerabilityChek(mFile.getOriginalFilename(), 0, "common", "fileup_img").equals("true")){
			    HeritFormBasedFileVO vo = new HeritFormBasedFileVO();

			    String tmp = mFile.getOriginalFilename();


			    String fileExtension = "";

		            if (tmp.lastIndexOf("\\") >= 0) {
		            	tmp = tmp.substring(tmp.lastIndexOf("\\") + 1);
		            }
		            if (tmp.lastIndexOf(".") >= 0) {
		            	fileExtension = tmp.substring(tmp.lastIndexOf(".") + 1);
		            }

		            vo.setFieldName(mFile.getName());
		            vo.setFileName(tmp);
		            vo.setContentType(mFile.getContentType());
		            //vo.setServerSubPath(getTodayString());
		            vo.setPhysicalName(getPhysicalFileName()+"."+fileExtension);
		            vo.setSize(mFile.getSize());

//		            if (tmp.lastIndexOf(".") >= 0) {
//		       	 	vo.setPhysicalName(vo.getPhysicalName());	// 2012.11 KISA 보안조치
//		            }

		            if (mFile.getSize() > 0) {
		            	InputStream is = null;

		            	try {
		            		is = mFile.getInputStream();
		            		//saveFile(is, new File(HeritWebUtil.filePathBlackList(where+SEPERATOR+vo.getServerSubPath()+SEPERATOR+vo.getPhysicalName())));
		            		saveFile(is, new File(HeritWebUtil.filePathBlackList(where+SEPERATOR+vo.getPhysicalName())));
		            	} finally {
		            		if (is != null) {
		            			is.close();
		            		}
		            	}
		            	list.add(vo);
		            }


		    }// LGU+ 보안 취약점 모듈 적용 (img 파일인지 점검) end


		}

		return list;
    }
 
Example 19
Source Project: mumu   File: UploadUtil.java    License: Apache License 2.0 4 votes vote down vote up
/** 上传文件处理(支持批量)
 * @throws IOException
 * @throws IllegalStateException */
public static List<String> uploadImage(HttpServletRequest request) throws IllegalStateException, IOException {
	CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
			request.getSession().getServletContext());
	List<String> fileNames = InstanceUtil.newArrayList();
	if (multipartResolver.isMultipart(request)) {
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Iterator<String> iterator = multiRequest.getFileNames();
		String pathDir = request.getSession().getServletContext()
				.getRealPath(uploadFileDir + DateUtils.currentTime());
		File dirFile = new File(pathDir);
		if (!dirFile.isDirectory()) {
			dirFile.mkdirs();
		}
		while (iterator.hasNext()) {
			String key = iterator.next();
			MultipartFile multipartFile = multiRequest.getFile(key);
			if (multipartFile != null) {
				String name = multipartFile.getOriginalFilename();
				// 默认文件格式为png图片
				if (name.indexOf(".") == -1 && "blob".equals(name)) {
					name = name + ".png";
				}
				String uuid = UUID.randomUUID().toString().replace("-", "");
				int lastIndexOf = name.lastIndexOf(".");
				if(lastIndexOf==-1){
					name=name + ".png";
				}
				lastIndexOf = name.lastIndexOf(".");
				String postFix=name.substring(lastIndexOf).toLowerCase();
				String fileName = uuid + postFix;
				String filePath = pathDir + File.separator + fileName;
				File file = new File(filePath);
				file.setWritable(true, false);

				multipartFile.transferTo(file);
				fileNames.add(file.getAbsolutePath());
			}
		}
	}
	return fileNames;
}
 
Example 20
@RequestMapping(value="/edms/call_ajax", method=RequestMethod.POST)
public String getFile(Model model, MultipartHttpServletRequest request, HttpServletResponse response){
	
	 Iterator<String> itr =  request.getFileNames();
	 
     MultipartFile multipart = request.getFile(itr.next());
   
	 try {
		  
		   
		 // access the file system folder or repository otherwise it creates it
		  File dir = createUploadDirectory("tmpFiles");

         // copies the file on server
        uploadAjaxFile(dir, multipart, model);
         
	} catch (IOException e) {
		return "single_upload_ajax_form";
	}
  
	return "view_ajax";
}