Java文件上传下载方法 :

/**
*上传
*/
public static String uploadFile(MultipartFile file) {
	String fileName = file.getOriginalFilename();	
	String name = fileName.substring(0, fileName.lastIndexOf("."));
	String extension = fileName.substring(fileName.lastIndexOf("."));

	String filePath = System.getProperty("user.dir") + "\\whnbgd\\";
	File targetFile = new File(filePath);
	// 第一步:判断文件是否为空
	if (file.isEmpty())
		return fileName + "文件为空";
	// 第二步:判断目录是否存在 不存在:创建目录
	if (!targetFile.exists()) {
		targetFile.mkdirs();
	}
	// 第三步:通过输出流将文件写入硬盘文件夹并关闭流
	BufferedOutputStream stream = null;
	// 防止文件覆盖
	String nowTime = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
	try {
		stream = new BufferedOutputStream(new FileOutputStream(filePath + name + nowTime + extension));
		stream.write(file.getBytes());
		stream.flush();
	} catch (IOException e) {
		e.printStackTrace();
	} finally {
		try {
			if (stream != null)
				stream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	return fileName + "上传成功";
}

/**
*下载
*
*/
public static void downloadNet(String urlStr, String wjcfdz, HttpServletResponse response) throws MalformedURLException {
	// 下载网络文件
	int bytesum = 0;
	int byteread = 0;

	URL url = new URL(urlStr);

	try {
		URLConnection conn = url.openConnection();
		InputStream inStream = conn.getInputStream();
		FileOutputStream fs = new FileOutputStream(wjcfdz);

		byte[] buffer = new byte[1204];
		int length;
		while ((byteread = inStream.read(buffer)) != -1) {
			bytesum += byteread;
			fs.write(buffer, 0, byteread);
		}
	} catch (FileNotFoundException e) {
		e.printStackTrace();
	} catch (IOException e) {
		e.printStackTrace();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值