SpringBoot上传文件到服务器返回文件地址

@ApiOperation(value = "app文件上传")
	@PostMapping("/fileUpload")
	public SuccessOutPut> appUploadFile(@RequestBody AppUploadFileList files, HttpServletRequest request) throws Exception {
		// 获取配置中的 服务器文件存储路径
		String uploadFilePath = ConstantConfig.UPLOAD_FILE_PYSICAlLPATH;

		StringBuffer uploadFilePathName; // 文件磁盘存储路径+文件名

		//获取读取图片前缀路径
		String serverIPPort = getServerIPPort(request);
		
		List results = new ArrayList();

		for (AppuploadFile multipartFile : files.getUploadFile()) {
			AppUploadFileResult result = new AppUploadFileResult();
			// 拼接路径+文件名,文件名重复性暂由客户端保障
			uploadFilePathName = new StringBuffer();
			uploadFilePathName.append(uploadFilePath).append("/").append(multipartFile.getFileName());

			BASE64Decoder decoder = new BASE64Decoder();//sun提供base64
			// Base64解码
			byte[] b = decoder.decodeBuffer(multipartFile.getFileCode());
			for (int i = 0; i < b.length; ++i) {
				if (b[i] < 0) {// 调整异常数据
					b[i] += 256;
				}
			}
			OutputStream out = new FileOutputStream(uploadFilePathName.toString());
			out.write(b);
			out.flush();
			out.close();
			//
			result.setFileName(multipartFile.getFileName());
			result.setFileUrl(getBackUrl(serverIPPort, multipartFile.getFileName()));
			results.add(result);
		}
		return new SuccessOutPut>(results);
	}

	/**
	 * 获取服务部署根路径 http:// + ip + port
	 * 
	 * @param request
	 * @return
	 */
	private String getServerIPPort(HttpServletRequest request) {
		//+ ":" + request.getServerPort()
		return request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
	}

	/**
	 * 获取文件回调url
	 * 
	 * @param serverName
	 *            服务路径
	 * @param fileName
	 *            文件名
	 * @return 回调url
	 */
	private String getBackUrl(String serverName, String fileName) {
		StringBuffer backUrl = new StringBuffer();

		String uploadFileVirPath = ConstantConfig.UPLOAD_FILE_VIRTUALPATH;
		backUrl.append(serverName).append(uploadFileVirPath).append("/").append(fileName);

		return backUrl.toString();
	}

菜鸟交流:1126802

你可能感兴趣的:(JAVA)