今天使用ssh框架实现了类似云盘的文件上传下载功能。其中遇到不少坑,现在爬起来整理一下经验。
整个流程是页面可以点击进行文件上传,服务器接收到上传的文件并保存到本地,然后把文件的路径保存到数据库中。下面直接上代码
用来接收服务器从数据查询的所有文件,把名字显示到页面
<c:forEach items="${list}" var="list" varStatus="status">
<span href="#" onclick="download(this)" id="${list.id}"
style="cursor:pointer">${list.name}</span><br />
</c:forEach>
jsp文件上传
<form action="${pageContext.request.contextPath}/ajax/core/DiscussAdmin.do?method=Yuninsert" method="post" enctype="multipart/form-data">
<input type="text" name="text" id="text" style="display:none">
<input type="file" name="file" />
<br/><br/>
<input type="submit" value="上传" />
</form>
js代码:点击文件名字直接下载。之前使用ajax,后来发现ajax无法将内存数据写到磁盘上。后来直接使用js跳转,在url后面直接拼接当前点击文件的id。
<script type="text/javascript">
window.onload=function (){
function getUrlParam(name) {
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); // 构造一个含有目标参数的正则表达式对象
var r = window.location.search.substr(1).match(reg); // 匹配目标参数
if (r != null) return unescape(r[2]); return null; // 返回参数值(云盘分为好多文件夹,这里获取当前进入的文 件夹)
}
var id = getUrlParam("id"); //从返回的参数取id
var textid = document.getElementById("text");
textid.value = id ;}
function download(obj){
var id = obj.id;
window.location.href= "${pageContext.request.contextPath}/ajax/core/DiscussAdmin.do?method=Yundownload&id="+id;
}</script>
后台文件上传代码:这里多了一步修改数据库字段长度的代码(可以忽略,因为博主是二次开发,库不在本地)
public void Yuninsert(ActionMapping map, ActionForm actionForm, HttpServletRequest req, HttpServletResponse res)
throws Exception {
System.out.println("come on Yuninsert");
Yunimpl impl = new Yunimpl();
impl.updatalenth();
Map filemap = FileUpload.uploadFile(req);
Yun yun = new Yun();
yun.setId(filemap.get("id") + "");
yun.setName(filemap.get("name") + "");
yun.setUrl(filemap.get("url") + "");
impl.Yuninsert(yun);
}
文件查询代码:这里根据每个分组的id进行查询:用session进行传值
public void Yunselect(ActionMapping map, ActionForm actionForm, HttpServletRequest req, HttpServletResponse res) {
System.out.println("come on Yunselect");
Yunimpl impl = new Yunimpl();
String id = req.getParameter("id");
HttpSession session = req.getSession();
session.setAttribute("list", impl.YunSelect(id));
}
文件下载代码:
public void Yundownload(ActionMapping map, ActionForm actionForm, HttpServletRequest req, HttpServletResponse res) {
String id = req.getParameter("id");
Yunimpl impl = new Yunimpl();
Yun yun = impl.selectByid(id);
FileUpload.downloadFile(yun,res);
}
文件上传下载主要类:
package com.news.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class FileUpload {
public static Map<String,String> uploadFile(HttpServletRequest req) throws Exception {
String savePath = req.getSession().getServletContext().getRealPath("/WEB-INF/dir");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("UTF-8");
Map map = new HashMap();
if (!ServletFileUpload.isMultipartContent(req)) {
return null;
}
List<FileItem> list = upload.parseRequest(req);
for (FileItem item : list) {
if (item.isFormField()) {
String name = item.getFieldName();
// 解决普通输入项的数据的中文乱码问题
String value = item.getString("UTF-8");
// value = new String(value.getBytes("iso8859-1"),"UTF-8");
System.out.println(name + "=" + value);
savePath = savePath + File.separator +value;
File file = new File(savePath);
if (!file.exists() && !file.isDirectory()) {
System.out.println(savePath + "目录不存在,需要创建");
file.mkdir();
System.out.println("创建成功!!!!!");
}
map.put("url", savePath);
map.put("id", value);
System.out.println("savePath :"+savePath);
} else {// 如果fileitem中封装的是上传文件
// 得到上传的文件名称,
String filename = item.getName();
System.out.println(filename);
if (filename == null || filename.trim().equals("")) {
continue;
}
filename = filename.substring(filename.lastIndexOf("\\") + 1);
InputStream in = item.getInputStream();
FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);
byte buffer[] = new byte[1024];
int len = 0;
while((len=in.read(buffer))>0){
//使用FileOutputStream输出流将缓冲区的数据写入到指定的目录(savePath + "\\" + filename)当中
out.write(buffer, 0, len);
}
map.put("name", filename);
in.close();
out.close();
item.delete();
System.out.println("文件上传成功!");
}
}
return map;
}
public static void downloadFile(Yun yun,HttpServletResponse response) {
try {
response.setCharacterEncoding("utf-8");
response.setHeader("Pragma", "No-Cache");
response.setHeader("Cache-Control", "No-Cache");
response.setDateHeader("Expires", 0);
response.setContentType("application/msexcel; charset=UTF-8");
response.setHeader("Content-disposition", "attachment; filename=" + URLEncoder.encode(yun.getName(), "UTF-8"));// 设定输出文件头
ServletOutputStream out = null;
FileInputStream in = new FileInputStream(yun.getUrl()+File.separator+yun.getName()); // 读入文件
out = response.getOutputStream();
out.flush();
int aRead = 0;
while ((aRead = in.read()) != -1 & in != null) {
out.write(aRead);
}
out.flush();
in.close();
out.close();
}catch (Exception e){
e.printStackTrace();
}
}
}
到此文件上传下载功能完成。下面是运行结果(纯后台请不要在乎美化)
首先文件分组:
上传下载效果图:
到此就完成了。欢迎各位大佬批评指正。谢谢!!!