使用Java servlet实现文件上传,主页和数据库都能看到刚刚添加的信息,上传的文件也能够下载,但字段信息显示的都是相同的,然后上传的txt文件我是在里面打了几个中文,下载下来的文件,文件名没错,但文件的内容变成了乱码
itemDao.java
ListItem.java
item.jsp
item-add.jsp
additem.java
download.java
将你的下载方法改一下:
@WebServlet("/File")
public class Download extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置请求和响应的字符编码为 UTF-8,以确保能正确处理中文字符。
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
// 获取请求参数中的文件名
String name = req.getParameter("fname");
// 设置响应的内容类型,根据文件类型设置相应的 MIME 类型
String contentType = getServletContext().getMimeType(name);
resp.setContentType(contentType != null ? contentType : "application/octet-stream");
// 在响应头中设置 Content-Disposition 为 attachment,表示将文件作为附件下载,同时指定文件名为编码后的文件名。
resp.addHeader("Content-Disposition", "attachment;filename=\"" + URLEncoder.encode(name, "utf-8") + "\"");
// 创建一个文件输入流,指向服务器上的待下载文件
FileInputStream is = new FileInputStream("D:/file/" + name);
// 获取响应输出流,使用字节流进行文件输出
OutputStream os = resp.getOutputStream();
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
// 关闭输入流和输出流。
is.close();
os.close();
}
}