Flask接口签名sign原理与实例代码浅析
208
2023-05-06
JavaWeb中上传和下载文件实例代码
一丶先引入上传下载的lib
二丶上传的的servlet
三丶下载的servlet
package com.test.action;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HtOJasZJwzvstpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/download")
public class FileDownloadAction extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
// 根据主键读取文件的真实名字 + 服务器上的名字
processDownload("1444442288605.png", "腾讯.png", request, response);
}
private boolean processDownload(String fileName, String saveName,
HttpServletRequest request, HttpServletResponse response) {
boolean success = true;
// 获取文件下载所在的路径
String path = request.getServletContext().getRealPath("/upload");
File fileLoad = new File(path, fileName); // 下载文件
long fileLength = fileLoad.length(); // 文件大小
byte[] buffer = new byte[1024]; // 缓冲字节数组
try {
response.reset();
response.setHeader("Content-disposition", "attachment;filename=\""
+ new String(saveName.getBytes("gb2312"), "ISO-8859-1") + "\"");
response.setContentType("application/octet-stream");
response.setHeader("Content_Length", String.valueOf(fileLength));
OutputStream os = response.getOutputStream();
FileInputStream in = new FileInputStream(fileLoad);
int hasRead = 0;
while ((hasRead = in.read(buffer)) != -1) {
os.write(buffer, 0, hasRead);
}
os.flush();
os.close();
in.close();
} catch (IOException e) {
success = false;
e.printStackTrace();
}
return success;
}
}
以上所述是给大家介绍的JavaWeb中上传和下载文件实例代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,会及时回复大家的。在此也非常感谢大家对我们网站的支持!
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~