上傳下載相關(guān)bug
該部分使用的jar包,請先導(dǎo)入到項(xiàng)目中。
上傳文件
最近在做一個(gè)上傳下載的例子,可是我上傳的時(shí)候碰到了以下異常:
因?yàn)樵搯栴}已解決,調(diào)出源碼:
一看就知道了是文件路徑寫錯(cuò)了,但是我仔仔細(xì)細(xì)的檢查了好幾遍,并沒有問題smartupload路徑對的下載出現(xiàn)問題,我重新后,啟動(dòng)第二次,成功上傳,這個(gè)我也不知道是因?yàn)槭裁础?/p>
我已經(jīng)在上傳的文件加中創(chuàng)建了一個(gè)a.txt文檔,以防止空文件夾不加載到服務(wù)器。此項(xiàng)原因,日后若再次遇到,便回來記錄。
原因:(此處預(yù)留)
注冊頁面的上傳頭像代碼:
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 {
//參數(shù):servlet對象,請求,響應(yīng),字符串(錯(cuò)誤頁面地址),是否使用session(false),緩沖區(qū)大小(int)字節(jié),緩沖區(qū)滿了溢出部分是否自動(dòng)輸出到輸出流(布爾值)
PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, false, 1024, true);
//初始化上傳文件操作
smartUpload.initialize(pageContext);
//設(shè)置編碼方式
smartUpload.setCharset("utf-8");

//上傳
smartUpload.upload();
//獲取文件信息
File file = smartUpload.getFiles().getFile(0);
String fileName = file.getFileName();
String contentType = file.getContentType();
//指定上傳路徑,注意空文件夾無法部署到服務(wù)器,
String uploadPath = "/uploadFiles/" + fileName;
//保存到指定位置,第二個(gè)參數(shù)為虛擬路徑
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();

}
}
}
下載文件 下載文件時(shí),單擊后頁面顯示,
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>
其中為用戶登錄時(shí)存入中的值。
登錄部分代碼:
@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 = "登錄成功!
尊敬的" + user.getName() + ",你好!";
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();
}
}
數(shù)據(jù)庫:
我原先這里存的是即完整的相對路徑,后來改成只存文件名。原來數(shù)據(jù)庫存入的值是//文件名,然后我在下載中又再次拼接了路徑:
String filename = req.getParameter("filename");
//就是這里,我又再拼接了一次
String path = "/uploadFiles/" + filename;
原因:我忘記了我在數(shù)據(jù)庫中的字段已經(jīng)存入完整路徑了,這里在加肯定頁面找不到。
下載彈框文件名是a標(biāo)簽href的的url
之后單擊下載的連接后,出現(xiàn)了彈框,但是文件名是我的名,下載下來的也是亂碼文件smartupload路徑對的下載出現(xiàn)問題,沒有后綴名。我就在仔細(xì)檢查了一遍,原來是因?yàn)槲襾G了個(gè)等號。囧!
請注意頭信息的=,我之前沒有這個(gè)等號!
@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;
//設(shè)置響應(yīng)頭信息和響應(yīng)類型
resp.setContentType("application/octet-stream");
//添加頭信息,指定編碼格式,防止中文亂碼
resp.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
//跳轉(zhuǎn)頁面
req.getRequestDispatcher(path).forward(req, resp);
//清空緩存區(qū)
resp.flushBuffer();
}
然后上傳下載都o(jì)k了。
哇,不得不說,我最近狀態(tài)不對啊!不說了,睡覺。
晚安。
sue
2021年3月13日00:20:19