飞鱼蓝空

导航

文件上传下载/文件格式转换

路径:request.getSession().getServletContext().getRealPath(path)

常用类:File,String

常用方法:

String name=fileStr.substring(0, fileStr.indexOf("."));//获取文件名

Process pro = Runtime.getRuntime().exec(command);//"command"---dos命令行 (本机系统执行dos命令)
pro.waitFor();//---等待dos命令执行完

代码:

/**
* 复制文件
* @param sourceFile file文件
* @param targetFile 移动路径
* @throws IOException
*/
public static void copyFile(File sourceFile, File targetFile) throws IOException {
BufferedInputStream inBuff = null;
BufferedOutputStream outBuff = null;
try {
// 新建文件输入流并对它进行缓冲
inBuff = new BufferedInputStream(new FileInputStream(sourceFile));

// 新建文件输出流并对它进行缓冲
outBuff = new BufferedOutputStream(new FileOutputStream(targetFile));

// 缓冲数组
byte[] b = new byte[1024 * 5];
int len;
while ((len = inBuff.read(b)) != -1) {
outBuff.write(b, 0, len);
}
// 刷新此缓冲的输出流
outBuff.flush();
} finally {
// 关闭流
if (inBuff != null)
inBuff.close();
if (outBuff != null)
outBuff.close();
}
}

/**

上传代码

*/

String savePath = request.getSession().getServletContext().getRealPath(path);
File folder = new File(savePath);

if (!folder.exists())
folder.mkdirs();
File file2 = new File(savePath + "/" + name);
if (!file2.exists()) {
file.transferTo(file2);//spring框架方法实现文件的上传
} else {
return "文件名重复";
}

/**

文件下载

*/

String uri = request.getParameter("filepath");

File file = new File(uri);

if (file.exists()) {

OutputStream outputStream = response.getOutputStream();
FileInputStream inputStream = new FileInputStream(file);

String fileName = new String(file.getName().getBytes("UTF-8"),"ISO-8859-1");
byte cache[] = new byte[1024];
// 设置response的Header
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(cache);


int n = 0;

while ((n = inputStream.read(cache)) != -1) {
outputStream.write(cache, 0, n);
}
inputStream.close();
toClient.flush();
toClient.close();
outputStream.close();
}

posted on 2016-09-22 16:05  飞鱼蓝空  阅读(277)  评论(0编辑  收藏  举报