通过smartupload插件上传
1:下载插件并导入
右击项目àbuild pathàconfigue build pathàlibrariesàadd jarsà
2:java代码
public class Smart extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//设置上传文件保存路径
String filePath = getServletContext().getRealPath ("/") + "images";
File file = new File(filePath);
if(!file.exists()){
file.mkdir();
}
SmartUpload su = new SmartUpload();
//初始化对象
su.initialize(getServletConfig(), req, resp);
//设置上传文件大小
su.setMaxFileSize(1024*1024*10);
//设置所有文件的大小
su.setTotalMaxFileSize(1024*1024*100);
//设置允许上传文件类型
su.setAllowedFilesList("txt,jpg,gif");
String result = "上传成功!";
//设置禁止上传的文件类型
try {
su.setDeniedFilesList("rar,jsp,js");
//上传文件
su.upload();
int count = su.save(filePath);
System.out.println("上传成功" + count + "个文件!");
}
catch (Exception e) {
result = "上传失败!";
e.printStackTrace();
}
req.setAttribute("result",result);
req.getRequestDispatcher("up.jsp").forward(req, resp);
}
}
2:下载
Jsp代码:(图片保存在images目录下)
<!--下载: <a href="Smartdown?filename=005.jpg">005.jpg</a>
--> <hr>
Java代码
public class Smartdown extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TO Auto-generated method stub
doPost(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String filename=request.getParameter("filename");
SmartUpload su=new SmartUpload();
su.setContentDisposition(null);
su.initialize(getServletConfig(), request, response);
try {
su.downloadFile("/images/"+filename);
} catch (SmartUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}