JAVA上传下载文件
文件上传下载 文件上传
/**
* @Title: uploadXML
* @Description: 文件上传
* @param fis
* @param path
* @param name
* 设定文件
* @return void 返回类型
* @throws
*/
public static void uploadXML(InputStream fis, String path, String
name) {
FileOutputStream fos = null;
try {
// 1、创建目录
File fileDir = new File(path);
if (!fileDir.exists()) {
fileDir.mkdir();
}
// 2、创建文件
File file = new File(path + File.separator + name);
if (!file.exists()) {
file.createNewFile();
}
// 3、上传文件到服务器
fos = new FileOutputStream(file);
byte[] b = new byte[1024];
int j = 0;
while ((j = fis.read(b)) > 0) {
fos.write(b, 0, j);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null) {
fos.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
}
文件下载
/**
* @Title: DownloadXML
* @Description: 文件下载
* @param response
* @param path
* @param name
* 设定文件
* @return void 返回类型
* @throws
*/
public static void downloadXML(HttpServletResponse response, String
path,String name) {
InputStream fis = null;
OutputStream os = null;
File file = null;
try {
String downloadpath = path + File.separator + name;
file = new File(downloadpath);
response.addHeader("Content-Disposition", "attachment;filename="+ new String(name.getBytes("gb2312"), "ISO8859-1"));
response.addHeader("Content-Length", "" + file.length());
fis = new BufferedInputStream(new FileInputStream(downloadpath));
os = new BufferedOutputStream(response.getOutputStream());
byte[] b = new byte[1024];
int j = 0;
while((j=fis.read(b))>0){
os.write(b, 0, j);
}
os.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (os != null) {
os.close();
}
if (file.exists()) {
file.delete();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}