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

The following examples show how to use org.springframework.web.multipart.MultipartHttpServletRequest#getFile() . 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
/**
 * 上传图片信息
 * 
 * @param request
 * @return
 */
@RequestMapping("uploadImage")
@ResponseBody()
public void uploadImage(MultipartHttpServletRequest request) {
	try {
	AppUser curUser = App.current().getUser();
	User user = userInfoService.findByUserId(curUser.getId());
	String label = request.getParameter("label");
	MultipartFile file = request.getFile("file");
		String imgStr = Images.toBase64(Files.getMimeType(file.getOriginalFilename()), file.getBytes());
		userInfoService.saveImage(user, imgStr, com.jlfex.hermes.model.UserImage.Type.AUTH, label);
	} catch (Exception e) {
		Logger.error(e.getMessage(), e);
		throw new ServiceException(e.getMessage(), e);
	}
}
 
Example 2
Source Project: fastdep   File: FastDepFileServlet.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Fast dep file service
 *
 * @param request  HttpServletRequest
 * @param response HttpServletResponse
 * @throws IOException
 */
@Override
protected void service(HttpServletRequest request,
                       HttpServletResponse response) throws IOException {
    String requestUri = request.getRequestURI();
    FileStorageUtil fileStorageUtil = new FileStorageUtil(this.fastDepFileProperties);
    String downloadUrl = this.fastDepFileProperties.getDownloadUrl();
    if (this.fastDepFileProperties.getUploadUrl().equals(requestUri)) {
        // HttpServletRequest to MultipartHttpServletRequest
        StandardServletMultipartResolver resolver = new StandardServletMultipartResolver();
        MultipartHttpServletRequest multipartRequest = resolver.resolveMultipart(request);
        MultipartFile files = multipartRequest.getFile(this.fastDepFileProperties.getFieldName());
        FileResponse fileResponse = fileStorageUtil.uploadFile(files);
        response.setContentType("text/json;charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        PrintWriter out = response.getWriter();
        ObjectMapper mapper = new ObjectMapper();
        String result = mapper.writeValueAsString(fileResponse);
        out.println(result);
        out.flush();
        out.close();
    } else if (requestUri.startsWith(downloadUrl)) {
        // download file
        fileStorageUtil.downloadFile(requestUri.substring(downloadUrl.length() + 1), request, response);
    }
}
 
Example 3
/**
 * 保存图片
 * @return
 */
@RequestMapping(value = "/doUpload",method ={RequestMethod.POST})
@ResponseBody
public AjaxJson doUpload(MultipartHttpServletRequest request,HttpServletResponse response){
	AjaxJson j = new AjaxJson();
	try {
		MultipartFile uploadify = request.getFile("file");
        /*byte[] bytes = uploadify.getBytes();
        String realFilename=uploadify.getOriginalFilename();
        String fileExtension = realFilename.substring(realFilename.lastIndexOf("."));
        String filename=UUID.randomUUID().toString().replace("-", "")+fileExtension;
        //String uploadDir = request.getSession().getServletContext().getRealPath("upload/img/commonweixin/");
        String uploadDir = upLoadPath + "/upload/img/commonweixin/";
        File dirPath = new File(uploadDir);
        if (!dirPath.exists()) {  
            dirPath.mkdirs();  
        }  
        String sep = System.getProperty("file.separator");  
        File uploadedFile = new File(uploadDir + sep  + filename);  
        FileCopyUtils.copy(bytes, uploadedFile);*/
		String filename = OSSBootUtil.upload(uploadify , "upload/img/commonweixin");
        j.setObj(filename);
        j.setSuccess(true);
		j.setMsg("保存成功");
	} catch (Exception e) {
		e.printStackTrace();
		j.setSuccess(false);
		j.setMsg("保存失败");
	}
	return j;
}
 
Example 4
@RequestMapping("/image")
@ResponseBody
public RestResponse questionUploadAndReadExcel(HttpServletRequest request) {
    MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartHttpServletRequest.getFile("file");
    long attachSize = multipartFile.getSize();
    String imgName = multipartFile.getOriginalFilename();
    try (InputStream inputStream = multipartFile.getInputStream()) {
        String filePath = fileUpload.uploadFile(inputStream, attachSize, imgName);
        userService.changePicture(getCurrentUser(), filePath);
        return RestResponse.ok(filePath);
    } catch (IOException e) {
        return RestResponse.fail(2, e.getMessage());
    }
}
 
Example 5
@RequestMapping(value = "upImg", method = RequestMethod.POST)
@ResponseBody
@ApiOperation(notes = "上传图片", value = "上传图片")
public Map<String, Object> uploadImg(HttpServletRequest request, HttpServletResponse response) {
    MultipartHttpServletRequest mhs = (MultipartHttpServletRequest) request;
    // 身份证截图
    MultipartFile imgUrl = mhs.getFile("file");
    try {

        String idCardFront = FileUpload.uploadFile(imgUrl, request);
        return ResponseUtil.getSuccessNoMsg(idCardFront);
    } catch (IOException e) {
        throw new CommonException("图片上传失败");
    }
}
 
Example 6
Source Project: attic-rave   File: PageApi.java    License: Apache License 2.0 5 votes vote down vote up
@ResponseBody
@RequestMapping(method = RequestMethod.POST, value = "import/omdl")
public RpcResult<Page> importPage(HttpServletRequest request, final HttpServletResponse response,
        @RequestParam final String pageName) {
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    final MultipartFile multipartFile = multipartRequest.getFile("omdlFile");
    return new RpcOperation<Page>() {
         @Override
         public Page execute() {
           return omdlService.importOmdl(multipartFile, pageName);
         }
    }.getResult();
}
 
Example 7
@PostMapping(value = "/upload")
public Result<?> upload(HttpServletRequest request, HttpServletResponse response) {
	Result<?> result = new Result<>();
	try {
		String ctxPath = uploadpath;
		String fileName = null;
		String bizPath = "files";
		String nowday = new SimpleDateFormat("yyyyMMdd").format(new Date());
		File file = new File(ctxPath + File.separator + bizPath + File.separator + nowday);
		if (!file.exists()) {
			file.mkdirs();// 创建文件根目录
		}
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		MultipartFile mf = multipartRequest.getFile("file");// 获取上传文件对象
		String orgName = mf.getOriginalFilename();// 获取文件名
		fileName = orgName.substring(0, orgName.lastIndexOf(".")) + "_" + System.currentTimeMillis() + orgName.substring(orgName.indexOf("."));
		String savePath = file.getPath() + File.separator + fileName;
		File savefile = new File(savePath);
		FileCopyUtils.copy(mf.getBytes(), savefile);
		String dbpath = bizPath + File.separator + nowday + File.separator + fileName;
		if (dbpath.contains("\\")) {
			dbpath = dbpath.replace("\\", "/");
		}
		result.setMessage(dbpath);
		result.setSuccess(true);
	} catch (IOException e) {
		result.setSuccess(false);
		result.setMessage(e.getMessage());
		log.error(e.getMessage(), e);
	}
	return result;
}
 
Example 8
Source Project: EasyHousing   File: UserController.java    License: MIT License 5 votes vote down vote up
@RequestMapping(value="changePhoto.do", method={RequestMethod.GET,RequestMethod.POST})
@ResponseBody
public ModelAndView changePhoto(HttpServletRequest request) throws IllegalStateException, IOException {
	ModelAndView modelAndView = new ModelAndView();
	modelAndView.setViewName("/MyHome/userCenter");
	HttpSession s = request.getSession();
	User user = (User) s.getAttribute("user");
	
	// 得到文件
	String path = request.getSession().getServletContext().getRealPath("upload");  
	MultipartHttpServletRequest multiRequest=(MultipartHttpServletRequest)request;
	Iterator iter=multiRequest.getFileNames(); 
	MultipartFile file=multiRequest.getFile(iter.next().toString()); 
       String fileName = file.getOriginalFilename();    
       File dir = new File(path,fileName);          
       if(!dir.exists()){  
       	dir.mkdirs();  
       }  
       //MultipartFile自带的解析方法  
       file.transferTo(dir); 
	
       try {
       	String filePath = path + "\\" + fileName;
       	System.err.println(filePath);
       	String name = new Date().toInstant().toString();
       	new Tool().upload(filePath, name);
       	user.setUserPhoto(String.valueOf("http://os8z6i0zb.bkt.clouddn.com/" + name));
       	userService.updateUser(user);
       } catch (Exception e) {
       	modelAndView.addObject("infoMessage", "上传头像失败TAT");
       	return modelAndView;
       }
       modelAndView.addObject("infoMessage", "上传头像成功!");
	return modelAndView;
}
 
Example 9
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 10
/**
 * 上传图片
 * 
 */
@RequestMapping(value = "doUpload", method = { RequestMethod.POST,RequestMethod.GET })
@ResponseBody
public AjaxJson doUpload(MultipartHttpServletRequest request,
    HttpServletResponse response) {
  AjaxJson j = new AjaxJson();
  try {
    //String randomSeed = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
    MultipartFile uploadify = request.getFile("file");
    //String realFilename = uploadify.getOriginalFilename();
    //String subsimage = realFilename.substring(realFilename.lastIndexOf("."));
    Date date = new Date();
    SimpleDateFormat formater = new SimpleDateFormat();
    formater.applyPattern("yyyy/MM");
    String dt = formater.format(date).toString().replace("/","");
    String imgurl ="/"+  dt + "/";
    //String filename = randomSeed + subsimage;
	//String uploadDir = ContextHolderUtils.getRequest().getSession().getServletContext().getRealPath("upload/img/fx");
	//String uploadDir = upLoadPath + "/upload/img/fx";

	//File dir = new File(uploadDir +imgurl);// 定义文件存储路径
    //log.info("doUpload 图片存储路径:{}",new Object[]{dir});
    //if (!dir.exists()) {
      //dir.mkdirs();
    //}
    //String sep = System.getProperty("file.separator");
    //OutputStream out = new FileOutputStream(dir + sep+ filename);
    //ImgUtil.scale(uploadify.getInputStream(), out, 0.7f);
    //uploadify.transferTo(dir);// 上传文件到存储路径
	String ossFileUrlBoot = OSSBootUtil.upload(uploadify , "upload/img/fx"+imgurl);
    //StringBuffer url = request.getRequestURL();
    //StringBuffer tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append("");
    j.setObj(ossFileUrlBoot);
    j.setSuccess(true);
    j.setMsg("保存成功");
  } catch (Exception e) {
    j.setSuccess(false);
    j.setMsg("保存失败");
    e.printStackTrace();
  }
  return j;
}
 
Example 11
/**
     * 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 12
/**
     * 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 13
/**
 * 上传图片
 * 
 */
@RequestMapping(value = "doUpload", method = { RequestMethod.POST,RequestMethod.GET })
@ResponseBody
public AjaxJson doUpload(MultipartHttpServletRequest request,
    HttpServletResponse response) {
  AjaxJson j = new AjaxJson();
  try {
    MultipartFile uploadify = request.getFile("file");
    /*String randomSeed = UUID.randomUUID().toString()
		  .replaceAll("-", "").toUpperCase();
    String realFilename = uploadify.getOriginalFilename();
    String subsimage = realFilename.substring(realFilename.lastIndexOf("."));
    String fileExtension = realFilename.substring(realFilename.lastIndexOf("."));
    Date date = new Date();
    SimpleDateFormat formater = new SimpleDateFormat();
    formater.applyPattern("yyyy/MM/dd");
    String dt = formater.format(date).toString();
    String imgurl ="/"+  dt + "/" + randomSeed + subsimage;
    String filename = randomSeed + subsimage;*/
	//String uploadDir = ContextHolderUtils.getRequest().getSession().getServletContext().getRealPath(filePath);
	//String uploadDir = upLoadPath + "/upload/img/goldeneggs";
	//原始上传方式
	/*File dir = new File(uploadDir +imgurl);// 定义文件存储路径
    log.info("doUpload 图片存储路径:{}",new Object[]{dir});
    if (!dir.exists()) {
      dir.mkdirs();
    }
    uploadify.transferTo(dir);// 上传文件到存储路径*/
	//压缩上传方式
	/*File dirPath = new File(uploadDir+"/"+  dt + "/");
    if (!dirPath.exists()) {
          dirPath.mkdirs();
      }
    String sep = System.getProperty("file.separator");
    OutputStream out = new FileOutputStream(dirPath + sep+ filename);
    ImgUtil.scale(uploadify.getInputStream(), out, 0.7f);*/
	// 高依赖版本 oss 上传工具
	String filename = OSSBootUtil.upload(uploadify , "upload/img/goldeneggs");

    j.setObj(filename);
    j.setSuccess(true);
    j.setMsg("保存成功");
  } catch (Exception e) {
    j.setSuccess(false);
    j.setMsg("保存失败");
    e.printStackTrace();
  }
  return j;
}
 
Example 14
Source Project: EasyHousing   File: AdminController.java    License: MIT License 4 votes vote down vote up
@RequestMapping(value = "adminAddUser.do", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView adminAddUser(HttpServletRequest request, User u) throws IllegalStateException, IOException {
	ModelAndView modelAndView = new ModelAndView();
	HttpSession session = request.getSession();
	//设置默认头像
	u.setUserPhoto("http://os8z6i0zb.bkt.clouddn.com/defaultPhoto.png");

	try {
		// 得到文件
		String path = request.getSession().getServletContext().getRealPath("upload");
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
		Iterator iter = multiRequest.getFileNames();
		MultipartFile file = multiRequest.getFile(iter.next().toString());
		String fileName = file.getOriginalFilename();
		File dir = new File(path, fileName);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		// MultipartFile自带的解析方法
		file.transferTo(dir);
		
		String filePath = path + "\\" + fileName;
		System.err.println(filePath);
		String name = new Date().toInstant().toString();
		new Tool().upload(filePath, name);
		u.setUserPhoto(String.valueOf("http://os8z6i0zb.bkt.clouddn.com/" + name));
	} catch (Exception e) {
		
	}
	
	User user = userService.selectUserByName(u);
	System.err.println("用户性别");
	System.err.println(u.getUserSex());
	if (session.getAttribute("addFail") == null)
		session.setAttribute("addFail", 0);
	if (user == null) {
		userService.insertUser(u);
		session.setAttribute("addFail", 0);
	} else {
		session.setAttribute("addFail", 1);
	}
	List<User> userList = userService.selectAllUser();
	session.setAttribute("userList", userList);
	modelAndView.setViewName("SystemUser/managerUser");
	return modelAndView;
}
 
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
@Nullable
public static Object resolveMultipartArgument(String name, MethodParameter parameter, HttpServletRequest request)
		throws Exception {

	MultipartHttpServletRequest multipartRequest =
			WebUtils.getNativeRequest(request, MultipartHttpServletRequest.class);
	boolean isMultipart = (multipartRequest != null || isMultipartContent(request));

	if (MultipartFile.class == parameter.getNestedParameterType()) {
		if (multipartRequest == null && isMultipart) {
			multipartRequest = new StandardMultipartHttpServletRequest(request);
		}
		return (multipartRequest != null ? multipartRequest.getFile(name) : null);
	}
	else if (isMultipartFileCollection(parameter)) {
		if (multipartRequest == null && isMultipart) {
			multipartRequest = new StandardMultipartHttpServletRequest(request);
		}
		return (multipartRequest != null ? multipartRequest.getFiles(name) : null);
	}
	else if (isMultipartFileArray(parameter)) {
		if (multipartRequest == null && isMultipart) {
			multipartRequest = new StandardMultipartHttpServletRequest(request);
		}
		if (multipartRequest != null) {
			List<MultipartFile> multipartFiles = multipartRequest.getFiles(name);
			return multipartFiles.toArray(new MultipartFile[0]);
		}
		else {
			return null;
		}
	}
	else if (Part.class == parameter.getNestedParameterType()) {
		return (isMultipart ? request.getPart(name): null);
	}
	else if (isPartCollection(parameter)) {
		return (isMultipart ? resolvePartList(request, name) : null);
	}
	else if (isPartArray(parameter)) {
		return (isMultipart ? resolvePartList(request, name).toArray(new Part[0]) : null);
	}
	else {
		return UNRESOLVABLE;
	}
}
 
Example 17
/**
     * 파일을 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 18
/**
     * 파일을 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 19
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 20
Source Project: lemon   File: OssRestController.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 上传文件,自动生成文件名. form模式,multipart模式
 */
public void postObjectMultipart(HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    logger.info("post multipart");
    logger.info("request : {}", request.getClass());

    MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;

    try {
        // req = multipartResolver.resolveMultipart(request);
        logger.info("file map : {}", req.getFileMap());
        logger.info("param map : {}", req.getParameterMap());

        OssAccess ossAccess = this.checkAuthorization(req, response);

        if (ossAccess == null) {
            return;
        }

        OssConfigDTO ossConfigDto = this.processBucket(req);
        logger.info("file map : {}", req.getFileMap());

        MultipartFile multipartFile = req.getFile("file");

        if (multipartFile == null) {
            logger.info("cannot find multipart file");

            return;
        }

        OssDTO ossDto = ossService.postObject(
                multipartFile.getInputStream(),
                ossConfigDto.getBucketName());

        Map<String, Object> data = new HashMap<String, Object>();
        data.put("objectName", ossDto.getObjectName());
        data.put("fileName", multipartFile.getOriginalFilename());
        data.put("fileSize", multipartFile.getSize());
        data.put("contentType", multipartFile.getContentType());

        BaseDTO baseDto = new BaseDTO();
        baseDto.setCode(200);
        baseDto.setData(data);

        response.setContentType("application/json");
        response.getWriter().write(jsonMapper.toJson(baseDto));
    } catch (Exception ex) {
        this.sendError(response, ex);
    }
}