上传下载相关bug
- 上传文件
- 下载文件
- 下载文件时,单击后页面显示pageNotFound,
- 下载弹框文件名是a标签href的servlet的url
该部分使用smartUpload的jar包,请先导入到项目中。
上传文件
最近在做一个上传下载的例子,可是我上传的时候碰到了以下异常:
因为该问题已解决,调出源码:
一看就知道了是文件路径写错了,但是我仔仔细细的检查了好几遍,并没有问题,我重新rebuild后,启动第二次,成功上传,这个我也不知道是因为什么。
我已经在上传的uploadFiles文件加中创建了一个a.txt文档,以防止空文件夹不加载到服务器。此项原因,日后若再次遇到,便回来记录。
原因:(此处预留)
注册页面的上传头像servlet代码:
package com.hllg.curriculum.servlet;
import com.hllg.curriculum.bean.User;
import com.hllg.curriculum.service.UserService;
import com.hllg.curriculum.service.impl.UserServiceImpl;
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;
/**
* @author HLLG
* @version 1.0
* @time 2021/03/09 Tue 16:07
*/
@WebServlet(urlPatterns = "/register")
public class UserRegisterServlet extends HttpServlet {
private static final long serialVersionUID = -6555577939985640277L;
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
SmartUpload smartUpload = new SmartUpload();
try {
//参数:servlet对象,请求,响应,字符串(错误页面地址),是否使用session(false),缓冲区大小(int)字节,缓冲区满了溢出部分是否自动输出到输出流(布尔值)
PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, false, 1024, true);
//初始化上传文件操作
smartUpload.initialize(pageContext);
//设置编码方式
smartUpload.setCharset("utf-8");
//上传
smartUpload.upload();
//获取文件信息
File file = smartUpload.getFiles().getFile(0);
String fileName = file.getFileName();
String contentType = file.getContentType();
//指定上传路径,注意空文件夹无法部署到服务器,
String uploadPath = "/uploadFiles/" + fileName;
//保存到指定位置,第二个参数为虚拟路径
file.saveAs(uploadPath, File.SAVEAS_VIRTUAL);
String username = smartUpload.getRequest().getParameter("username");
String password = smartUpload.getRequest().getParameter("userpwd1");
UserService userService = new UserServiceImpl();
User user = new User();
user.setName(username);
user.setPassword(password);
user.setProfileName(fileName);
int addUser = userService.addUser(user);
if (addUser > 0) {
resp.getWriter().println("<script>alert('注册成功');location='index.jsp'</script>");
} else {
resp.getWriter().println("<script>alert('注册失败');location='register.jsp'</script>");
}
} catch (SmartUploadException e) {
e.printStackTrace();
}
}
}
下载文件
下载文件时,单击后页面显示pageNotFound,
jsp页面部分代码:
<c:choose>
<c:when test="${profileName!=null && profileName!=''&& criticism.userId==id}">
<a href="/profileDownload?filename=${profileName}"><img src="/uploadFiles/${profileName}" class="img-circle" width="60px" height="60px"></a>
</c:when>
<c:otherwise>
<img src="img/profile.jpg" class="img-circle" width="60px" height="60px">
</c:otherwise>
</c:choose>
其中profileName为用户登录时存入session中的值。
登录部分代码:
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String username = req.getParameter("username");
String password = req.getParameter("userpwd");
UserService userService = new UserServiceImpl();
User user = userService.userLoginCheck(username, password);
if (user.getName() != null) {
String message = "登录成功!<br/>尊敬的<b>" + user.getName() + "</b>,你好!";
HttpSession session = req.getSession();
session.setAttribute("id", user.getId());
session.setAttribute("user", user.getName());
session.setAttribute("credit", user.getCredit());
session.setAttribute("profileName", user.getProfileName());
session.setAttribute("msg", message);
Cookie cookie = new Cookie("username", username);
resp.addCookie(cookie);
resp.sendRedirect("/queryAll");
} else {
PrintWriter writer = resp.getWriter();
writer.print("<script>alert('登录失败,请重试!');location.href='/index.jsp';</script>");
writer.close();
}
}
数据库:
我原先这里存的是profileAddress即完整的相对路径,后来改成只存文件名。原来数据库存入的值是/uploadFiles/文件名,然后我在下载servlet中又再次拼接了路径:
String filename = req.getParameter("filename");
//就是这里,我又再拼接了一次
String path = "/uploadFiles/" + filename;
原因:我忘记了我在数据库中的字段已经存入完整路径了,这里在加肯定页面找不到。
下载弹框文件名是a标签href的servlet的url
之后单击下载的连接后,出现了弹框,但是文件名是我的servlet名,下载下来的也是乱码文件,没有后缀名。我就在仔细检查了一遍,原来是因为我丢了个等号。囧!
请注意头信息的filename=,我之前没有这个等号!
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String filename = req.getParameter("filename");
String path = "/uploadFiles/" + filename;
//设置响应头信息和响应类型
resp.setContentType("application/octet-stream");
//添加头信息,指定编码格式,防止中文乱码
resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
//跳转页面
req.getRequestDispatcher(path).forward(req, resp);
//清空缓存区
resp.flushBuffer();
}
然后上传下载都ok了。
哇,不得不说,我最近状态不对啊!不说了,睡觉。
晚安。
sue
2021年3月13日00:20:19