首先需要第三方的smartupload.jar包
(1) 文件的上传
// 1.定义SmartLoad对象
SmartUpload upload = new SmartUpload();
upload.setCharset("utf-8");// 设置编码格式
// 2.初始化upload
upload.initialize(this.getServletConfig(), request, response);
// 3.上传的配置
upload.setMaxFileSize(1024 * 1024 * 1);// 设置文件大小
upload.setTotalMaxFileSize(1024 * 1024 * 10); // 设置文件总的大小
upload.setAllowedFilesList("jpg,gif");// 设置文件上传格式
try {
upload.setDeniedFilesList("bat,exe");// 设置不能上传的文件格式
} catch (SQLException e) {
e.printStackTrace();
}
// 4.获取request对象
Request req = upload.getRequest();
try {
upload.upload();// 上传文件
upload.save("/upload"); // 保存文件到根目录下(服务器下项目的根目录下)
} catch (SmartUploadException e) {
e.printStackTrace();
}
String filename = upload.getFiles().getFile(0).getFileName();// 获得上传的文件名
//获得用户输入的参数信息
String name = req.getParameter("name");
double price = Double.parseDouble(req.getParameter("price"));
int num = Integer.parseInt(req.getParameter("num"));
String size = req.getParameter("size");
String picture = filename;
//实例化一个对象
ClothBean cloth = new ClothBean(name, price, num, size, picture);
ClothDAO clothDao = new ClothDAO();
//添加衣服
boolean b = clothDao.addCloth(cloth);
if (b) {
request.getRequestDispatcher("ShowClothServlet").forward(request,response);
}
(2) 文件的下载
// 下载服务器上的图片
String filename = request.getParameter("filename");// 得到下载文件的名字
// 创建一个实例
SmartUpload upload = new SmartUpload();
// 初始化
upload.initialize(this.getServletConfig(), request, response);
// 禁止浏览器打开文件
upload.setContentDisposition(null);
// 从服务器上下载文件
try {
upload.downloadFile("/upload/" + filename);
} catch (SmartUploadException e) {
e.printStackTrace();
}