此处是前台代码,上传文件框,下载文件链接。
<form method="post" action="" id="form1" name="form1"
enctype="multipart/form-data">
<table width="100%" border="0" cellspacing="0" cellpadding="0">
<tr>
<td><img src="../images/arrow-1.gif" width="11" height="12">Excel上传:</td>
</tr>
<tr>
<td width="69%"><div align="left">
<img src="../images/space.gif" width="40" height="8"> <input
name="fujian_content" id="fileName" type="file" size="28">
<input type="submit" id="butten" name="button" value="上传"
onClick="btnsave_fujian(this);"> <a
href="${pageContext.request.contextPath}/file/downloadMoBan.do?xlsName=fwjfModel.xls"
target="_blank">[ 积分上传模版下载 ]</a>
</div></td>
<td width="25%" height="30"><div id='KB1Parent' class='parent'>
</div></td>
<td width="31%" height="30"><div id='KB6Parent' class='parent'> </div></td>
</tr>
</table>
<script type="text/javascript">
function btnsave_fujian(obj) {
//var sf_content = frm1.fujian_content.value;
var fileName = $("#fileName").val();
var ext = fileName.slice(fileName.lastIndexOf(".") + 1).toLowerCase();//获取文件后缀名
var flag = true;
if (document.getElementById("fileName").value == null
|| document.getElementById("fileName").value == "") {
alert("请选择上传文件");
flag = false;
return false;
}
if ("xls" != ext) {
alert("只能上传Excle文件");
flag = false;
return false;
}
if (flag) {
var url = "${pageContext.request.contextPath}/file/uploadFile.do";
//更改form的action
$("#form1").attr("action", url);
$("#form1").submit();
$("#butten").attr("disabled", "disabled");
}
}
</script>
后台代码:
- 文件下载
- 文件下载很简单,以流的方式下载。
@RequestMapping("downloadMoBan")
public void downloadMoBan(HttpServletResponse response, String xlsName) throws Exception {
try {
// path是指欲下载的文件的路径。
String path = FuwuFileUpload.class.getClassLoader().getResource("/").getPath();
path = path.replace('/', '\\'); // 将/换成\
// path=path.replace("file:", ""); //去掉file:
path = path.replace("classes\\", ""); // 去掉class\
path = path.substring(1); // 去掉第一个\,如 \D:\JavaWeb...
path += "upload\\";
path += xlsName;
File file = new File(path);
// 取得文件名。
String filename = file.getName();
// 取得文件的后缀名。
String ext = filename.substring(filename.lastIndexOf(".") + 1).toUpperCase();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(filename.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
- 文件上传。并修改保存文件名
@RequestMapping("uploadFile")
public String uploadFile(HttpServletResponse response, HttpServletRequest request,
@RequestParam(value = "fujian_content") MultipartFile file) throws Exception {
String path = FuwuFileUpload.class.getClassLoader().getResource("/").getPath();
path = path.replace('/', '\\'); // 将/换成\
// path=path.replace("file:", ""); //去掉file:
path = path.replace("classes\\", ""); // 去掉class\
path = path.substring(1); // 去掉第一个\,如 \D:\JavaWeb...
path += "upload";
System.out.println("pathpath:" + path);
System.out.println("后台输出:" + file.getOriginalFilename());// 打印出文件名
// 上传的文件名
String uploadName = file.getOriginalFilename();
// 获取后缀名
String[] strArray = uploadName.split("\\.");
int suffixIndex = strArray.length - 1;
String exe = strArray[suffixIndex];
// 组装服务器文件名
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String fileName = sdf.format(new Date());//服务器保存新文件名
fileName = fileName + "." + exe;//文件名+后缀名
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
sfu.setHeaderEncoding("UTF-8"); // 处理中文问题
List<FileItem> fileItems = sfu.parseRequest(request); // 解码请求
//以下是创建文件
String filePath = path + "\\" + fileName;//文件路径+文件全名
System.out.println("filePathfilePathfilePath:" + filePath);
File file2 = new File(fileName);
//若文件不存在,创建文件
if (file2.exists()) {
file2.createNewFile();
}
// 输入流
InputStream in = file.getInputStream();
// 输出流
OutputStream out = new FileOutputStream(filePath, true);
//将上传文件内容,写进服务器创建的新文件。
try {
byte[] buffer = new byte[1024];
while (true) {
int byteRead = in.read(buffer);
if (byteRead == -1)
break;
out.write(buffer, 0, byteRead);
}
}
catch (MalformedURLException ex) {
// System.err.println("写入新文件错误");
} finally {
//关闭输入流,输出流
if (in != null)
in.close();
if (out != null) {
out.close();
}
}
}