ssm+vue 前后台分离 之 前端 图片上传到后台





 

后台:

controller:

@RequestMapping(value = "/addAcceptShops", method = RequestMethod.POST)
    @ResponseBody
    // @LoginAnnot
    public ExecuteResult addMyAddress(@Valid AcceptShopsBean acceptShopsBean, Errors errors,
            MultipartHttpServletRequest request) {

        acceptShopsService.addAcceptShops(acceptShopsBean, request);
        return new ExecuteResult(StatusCode.OK, new HashedMap());
    }

service:

/**
	 * 添加商品
	 * 
	 * @param  
	 */
	@Transactional(readOnly = false, propagation = Propagation.REQUIRED)
	public ExecuteResult addAcceptShops(AcceptShopsBean acceptShopsBean, MultipartHttpServletRequest request) {
		acceptShopsBean.setId(Utils.uuid());
		acceptShopsBean.setUserId(AuthContext.getUserId());
		Map result = fileUpload(request);
		if (null == result) {
			return new ExecuteResult(StatusCode.PIC_FAIL, new HashedMap());
		}
		acceptShopsBean.setId(Utils.uuid());
		String[] path = result.get("path").split(",");
		String[] imgLoadPath = result.get("imgLoadPath").split(",");
		acceptShopsBean.setImgPath(path[0]);
		acceptShopsBean.setImgLoadPath(imgLoadPath[0]);
		acceptShopsBean.setStatus("0");// 未处理
		if (acceptDao.addAcceptShops(acceptShopsBean) != 1) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return new ExecuteResult(StatusCode.BAD_REQUEST_ADDRESS, new HashMap<>());
		}
		return new ExecuteResult(StatusCode.OK, new HashMap<>());
	}

 

上传方法:

private int i = 0;
	public Map fileUpload(MultipartHttpServletRequest request) {
		Map imgInfo = null;
		// 存放多个图片信息
		List imgPathList = new ArrayList();
		List imgLoadPathList = new ArrayList();

		Iterator fileNames = request.getFileNames();
		while (fileNames.hasNext()) {
			String path = "";
			MultipartFile file = request.getFile(fileNames.next());
			String fileName = file.getOriginalFilename();
			// 创建文件目录
			File filePath = null;
			if (ProjectConstants.PRO_DEBUG) {
				String debugPath = request.getSession().getServletContext().getRealPath("fileDir");
				filePath = new File(debugPath.concat(File.separator).concat(ProjectConstants.PIC_PATH_TYPE.CKEDITOR)
						.concat(File.separator).concat(DateUtils.getDate("yyyyMMdd")));
			} else {
				filePath = new File(
						ProjectConstants.PIC_PATH.concat(File.separator).concat(DateUtils.getDate("yyyyMMdd")));
			}
			if (!filePath.exists()) {
				filePath.mkdirs();
			}

			// 写入绝对路径
			String imageName = DateUtils.getDate("yyyyMMddHHmmss").concat(String.valueOf(i)).concat(".jpg");
			File fileSrc = new File(filePath, imageName);
			try (FileOutputStream fos = new FileOutputStream(fileSrc);
					InputStream inputStream = file.getInputStream();) {
				byte[] bb = new byte[1024];
				int read = -1;
				while ((read = inputStream.read(bb)) != -1) {
					fos.write(bb, 0, read);
				}
				path = fileSrc.getCanonicalPath();
				String ip = "";
				if (ProjectConstants.PRO_DEBUG) {
					ip = request.getRemoteAddr();
				} else {
					ip = " 网址";

				}
				String src = request.getScheme() + "://" + ip
						+ (request.getServerPort() == 80 ? "" : ":".concat(request.getServerPort() + ""))
						+ request.getContextPath() + "/acceptShops/show/" + DateUtils.getDate("yyyyMMdd") + "/"
						+ imageName;
				// 记录图片路径
				imgPathList.add(path);
				imgLoadPathList.add(src);

			} catch (Exception e) {
				e.printStackTrace();
			}
			imgInfo = new HashMap();
			i++;
		}
		// 返回图片存放路径
		if (null == imgInfo) {
			return null;
		}
		imgInfo.put("path", String.join(",", imgPathList));
		imgInfo.put("imgLoadPath", String.join(",", imgLoadPathList));
		return imgInfo;
	}

 上传后需要读取:

controller:


	/**
	 * 读取收当图片
	 * 
	 * @param fileName
	 * @param imgName
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/show/{fileName}/{imgName}", method = RequestMethod.GET)
	public void fileReLoad(@PathVariable String fileName, @PathVariable String imgName, HttpServletRequest request,
			HttpServletResponse response) {
		acceptShopsService.fileReLoad(fileName, imgName, request, response);
	}

 

service:

	public synchronized void fileReLoad(String fileName, String imgName, HttpServletRequest request,
			HttpServletResponse response) {
		ServletOutputStream outputStream = null;
		FileInputStream fis = null;
		try {
			response.setContentType("image/jpg");
			outputStream = response.getOutputStream();
			// 读取图片路径
			File file = null;
			if (ProjectConstants.PRO_DEBUG) {
				String debugPath = request.getSession().getServletContext().getRealPath("fileDir");
				file = new File(debugPath.concat(File.separator).concat(ProjectConstants.PIC_PATH_TYPE.CKEDITOR)
						.concat(File.separator).concat(fileName), imgName.concat(".jpg"));
			} else {
				file = new File(ProjectConstants.PIC_PATH.concat(File.separator).concat(fileName),
						imgName.concat(".jpg"));
			}
			if (file.exists()) {
				if (file.exists()) {
					fis = new FileInputStream(file);
					byte[] bb = new byte[1024];
					int read = -1;
					while ((read = fis.read(bb)) != -1) {
						outputStream.write(bb, 0, read);
					}
					fis.close();
					fis = null;
				}
			}
			outputStream.flush();
			outputStream.close();

			outputStream = null;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

 

 

搞定!

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

你可能感兴趣的:(ssm+vue 前后台分离 之 前端 图片上传到后台)