JAVA文件上传和下载

文件上传java后台的处理代码:

/**
	 * 上传文件
	 * 
	 * @param session
	 * @param file
	 * @return
	 *
	 */
	@RequestMapping(value = "sys/file/fileUpload", produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String fileUpload(HttpSession session, @RequestParam(value = "file", required = true) MultipartFile file) {
		String path = Property.getProperty("fileUpload.path");//文件存储的位置

		File dir = new File(path);
		if (!dir.exists()) {
			dir.mkdir();
		}

		String filename = "";
		if (!file.isEmpty()) {
			// log.debug(session.getServletContext().getRealPath(path));
			try {
				// 用UUID而不是时间戳
				filename = UUID.randomUUID().toString() + "____" + file.getOriginalFilename();

				// 文件保存路径
				String filePath = path + "/" + filename;
				// 转存文件
				file.transferTo(new File(filePath));

			} catch (Exception e) {
				log.error(CustomStringUtils.getExceptionInfo(e));
				return JSONUtil.toJsonString(new JsonResult(-1, "上传发生错误!", null));
			}
		}
		log.info("上传了文件" + filename);
		return JSONUtil.toJsonString(new JsonResult(1, "", filename));
	}

java后台下载文件:

	/**
	 * 下载文件
	 * 
	 * @param session
	 * @param filename
	 * @return
	 * @throws IOException
	 *
	 */
	@RequestMapping(value = "sys/file/fileDownload")
	public ResponseEntity<byte[]> download(HttpSession session, @RequestParam("filePath") String filename)
			throws IOException {
		String path = Property.getProperty("fileUpload.path");//文件存储的位置
		String filepath = path + "/" + filename;

		File file = new File(filepath);
		if (!file.exists()) {
			// return JSONUtil.toJsonString(new JsonResult(-1, "文件未找到!", null));
			log.error("文件没有找到!    " + filepath);
			throw new RuntimeException("文件没有找到!");
		}

		String dfileName = filename.split("____")[1];
		dfileName = new String(dfileName.getBytes("utf-8"), "ISO_8859_1");
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", dfileName);
		return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.OK);
	}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值