文件上传
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
try {
/*以上两行不能颠倒,否则会出现乱码*/
SmartUpload su = new SmartUpload();
// 设置允许上传的文件
su.setAllowedFilesList("txt,jpg");
// 获取config对象
ServletConfig config = this.getServletConfig();
// 上传初始化
su.initialize(config, request, response);
// 上传文件
su.upload();
// 读取网站当前实际物理路径
String rootPath = config.getServletContext().getRealPath("/");
// 打印获取的当前路径
System.out.println(rootPath);
String uname = su.getRequest().getParameter("uname");
// 根据用户名创建一个目录专门保存用户图片
File file = new File(rootPath+uname);
if (!file.exists()) {
file.mkdir();
}
// 将上传文件全部保存到指定目录
int count = su.save(file.getAbsolutePath());
System.out.println("打印count"+count);
out.print("保持成功");
} catch (Exception e) {
out.print("保存失败");
e.printStackTrace();
}
out.close();
}
文件下载
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
SmartUpload su = new SmartUpload();
su.initialize(this.getServletConfig(), request, response);
su.setContentDisposition(null);
String rootPath = this.getServletConfig().getServletContext().getRealPath("/");
try {
su.downloadFile(rootPath+"/ming.txt");
} catch (SmartUploadException e) {
e.printStackTrace();
}
}