---
title: "附件的上传和下载"
author: "hlbng"
date: "2009-06-01T09:09:07Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-06-01T09:09:07Z"
id: 399389
url: "https://hlbng.iteye.com/blog/399389"
---

1.附件的上传：

a.定义附件保存路径：

```
String fileURL = servlet.getServletContext().getRealPath(File.separator);
String filePath = "attachment" + File.separator + "file";
```

 

b.获取上传的附件：

```
FormFile file = fileForm.getPicFile();
```

c.上传附件：

```
upLoadFile(file, fileURL + filePath);
```

 

d.upLoadFile函数：

```
public boolean upLoadFile(FormFile formFile, String filepath)
		throws FileNotFoundException, IOException {
	// 得到文件的路径

	String dirpath = filepath;
	File dir = new File(dirpath);
	// 判断文件夹是否存在
	boolean dirflag = dir.exists();

	if (!dirflag) {
		// 不存在先创建,然后再创建子文件夹
		dir.mkdirs();
		// 可以创建子文件下的字文件夹
		// dir.mkdirs();
	}
	// 显示相应文件夹下的所有文件
	String[] list = dir.list();
	// 此循环控制是否插入重复的资料
	for (int i = 0; i < list.length; i++) {
		if (formFile.getFileName().equals(list[i])) {
			return false;
		}
	}
	InputStream stream = formFile.getInputStream();
	OutputStream bos = new FileOutputStream(dirpath + File.separator
			+ formFile.getFileName());
	int bytesRead = 0;
	byte[] buffer = new byte[8192];
	// 将文件写入服务器
	while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
		bos.write(buffer, 0, bytesRead);
	}
	bos.close();
	stream.close();
	return true;
}
```

2.附件的下载：

```
private static final String CONTENT_TYPE = "text/html; charset=GBK";

public static void getFile(HttpServletResponse response,
		HttpServletRequest request, String _filepath) throws Exception {
	response.setContentType(CONTENT_TYPE);

	String filePath = _filepath;
	File file = new File(filePath);
	String filename = new String(file.getName().getBytes("iso-8859-1"),
			"gbk");
	response.setContentType("application/x-msdownload");
	response.setContentLength((int) file.length());
	response.setHeader("Content-Disposition", "attachment;filename="
			+ new String(filename.getBytes("gbk"), "iso-8859-1"));
	FileInputStream fis = new FileInputStream(file);
	BufferedInputStream buff = new BufferedInputStream(fis);

	byte[] b = new byte[1024];// 相当于我们的缓存

	long k = 0;// 该值用于计算当前实际下载了多少字节

	// 从response对象中得到输出流,准备下载

	OutputStream myout = response.getOutputStream();

	// 开始循环下载

	while (k < file.length()) {

		int j = buff.read(b, 0, 1024);
		k += j;

		// 将b中的数据写到客户端的内存
		myout.write(b, 0, j);

	}

	// 将写入到客户端的内存的数据,刷新到磁盘
	myout.flush();

	//
	}
}
```