• 图片上传代码-旧的实现方式,项目中已删除,发表做备用


        项目中的图片上传,经过了3个阶段。

    1.实现单个图片的上传。

    2.实现多个图片的上传。

      为了兼容和更多的适应性,统一采用多个图片上传的接口。

     3.简化多个图片的上传。

       前端代码和后端Controller代码,都做到复用。


       下面的代码是,单个图片和多个图片的上传。

       前端图片上传用的是WebUploader

    /**
     * 图片上传控制器
     */
    //@Controller
    @Deprecated
    public class ImageController extends BaseController {
    
    	@Resource
    	private PhotoService borrowerPhotoService;
    
    	@Resource
    	private GlobalConfig globalConfig;
    
    	//@RequestMapping("/home/idCardImageUpload")
    	@Deprecated
    	public void idCardImageUpload(HttpServletRequest request,
    			HttpServletResponse response) throws IllegalStateException,
    			IOException {
    		// 定义上传路径
    		String imagePath = globalConfig.getImageUploadPath();
    		
    		JSONObject jsonObject = new JSONObject();
    		response.setContentType("text/html;charset=UTF-8");
    
    		// 创建一个通用的多部分解析器
    		CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
    				request.getSession().getServletContext());
    
    		// 判断 request 是否有文件上传,即多部分请求
    		boolean multipart = multipartResolver.isMultipart(request);
    		if (!multipart) {
    			jsonObject.put("success", false);
    			jsonObject.put("fileName", "");
    			returnJsonObject(response, jsonObject);
    			return;
    		}
    		// 转换成多部分request
    		String finalFileName = CommonUtil.handleFileList(request, imagePath);
    		jsonObject.put("success", true);
    		jsonObject.put("fileName", finalFileName);
    		returnJsonObject(response, jsonObject);
    
    	}
    
    	/**
    	 * 单独图片上传
    	 */
    	@Deprecated
    	@RequestMapping(value = "/idCardImageUpload2", method = RequestMethod.POST)
    	public void uploadOneFile(HttpServletRequest request, Model model,
    			HttpServletResponse response) {
    		BaseUser u = getCurrentUser();
    		JSONObject jsonObj = new JSONObject();
    		response.setContentType("text/html;charset=UTF-8");
    		String imagePath = (String) BasePropertyConfigurer
    				.getContextProperty("idCardImageUploadPath");
    		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    		CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartRequest
    				.getFile("Filedata");
    		String fileName = commonsMultipartFile.getOriginalFilename();
    		model.addAttribute("fileName", fileName);
    		// TODO
    		String[] strs = fileName.split("\.");
    		if (strs.length != 2) {// 图片名称不能有'.'
    			model.addAttribute("flag", false);
    			model.addAttribute("message", "图片命名格式错误!");
    			jsonObj.put("success", false);
    			returnJsonObject(response, jsonObj);
    			return;
    		}
    		try {
    			fileName = AES.Encrypt(strs[0], CommonUtil.uniqueFileName()
    					.substring(1))
    					+ "." + strs[1];
    		} catch (Exception e1) {
    			e1.printStackTrace();
    		}
    		if (!commonsMultipartFile.isEmpty()) {
    			File imageDir = new File(imagePath);
    			if (!imageDir.exists())
    				imageDir.mkdirs();
    			File targetFile = new File(imagePath + fileName);
    			try {
    				commonsMultipartFile.transferTo(targetFile);
    
    				model.addAttribute("flag", true);
    			} catch (IllegalStateException e) {
    				e.printStackTrace();
    				model.addAttribute("flag", false);
    				model.addAttribute("message", e.getMessage());
    			} catch (IOException e) {
    				e.printStackTrace();
    				model.addAttribute("flag", false);
    				model.addAttribute("message", e.getMessage());
    			}
    
    			Photo photo = new Photo();
    			photo.setSort(0);
    			photo.setUid(Long.valueOf(u.getId()));
    			photo.setUrl("idCard/" + targetFile.getName());
    			photo.setStatus(1);
    			photo.setAddtime(new Date());
    			borrowerPhotoService.save(photo);
    		}
    		jsonObj.put("success", true);
    		returnJsonObject(response, jsonObj);
    	}
    
    	@Deprecated
    	@RequestMapping(value = "/doadd22", method = RequestMethod.POST)
    	public void doAdd(Photo photo, HttpServletRequest request, Model model,
    			HttpServletResponse response) {
    		JSONObject jsonObj = new JSONObject();
    		response.setContentType("text/html;charset=UTF-8");
    		String imagePath = globalConfig.getImageUploadPath();
    		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    		CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartRequest
    				.getFile("Filedata");
    		String fileName = handleFileName(model, commonsMultipartFile);
    
    		if (!commonsMultipartFile.isEmpty()) {
    			File imageDir = new File(imagePath);
    			if (!imageDir.exists())
    				imageDir.mkdirs();
    			File targetFile = new File(imagePath + "/" + fileName);
    			try {
    				commonsMultipartFile.transferTo(targetFile);
    			} catch (IllegalStateException | IOException e) {
    				e.printStackTrace();
    			}
    
    			photo.setUrl(targetFile.getName());
    			photo.setStatus(PhotoStatus.NORMAL.getCode());
    			// photoService.save(photo);
    		}
    
    		jsonObj.put("success", true);
    		returnJsonObject(response, jsonObj);
    	}
    
    	private String handleFileName(Model model,
    			CommonsMultipartFile commonsMultipartFile) {
    		String fileName = commonsMultipartFile.getOriginalFilename();
    		model.addAttribute("fileName", fileName);
    		String suffix = ".jpg";
    		int index = fileName.lastIndexOf(".");
    		if (index != -1) {
    			suffix = fileName.substring(index, fileName.length());
    		}
    		try {
    			fileName = MD5Util.md5(date()) + suffix;
    		} catch (Exception e1) {
    			e1.printStackTrace();
    		}
    		return fileName;
    	}
    
    	private String date() {
    		return DateFormatUtil.format(new Date(), "yyyyMMddHHmmssSSS")
    				.substring(1);
    	}
    }


  • 相关阅读:
    Lua中如何实现类似gdb的断点调试—06断点行号检查与自动修正
    211. 添加与搜索单词 数据结构设计 (JAVA)
    SuperSocket 1.5 stable发布
    SuperWebSocket发布0.1版本
    无需等待,SuperSocket 1.4 SP1 发布了!
    SuperSocket 1.5 文档列表
    SuperSocket 1.4 SP2 发布了!
    imx6ull spiimx.c 驱动接收导致内存问题
    nacos下载、安装、使用,SpringCloud、SpringBoot、SpringCloudAlibaba版本匹配、openfeign、loadbalancer、nacos配置中心
    idea配置显示Run Dashboard,引入自定义jar包
  • 原文地址:https://www.cnblogs.com/qitian1/p/6462820.html
Copyright © 2020-2023  润新知