.format(Calendar.getInstance().getTime())// 得到系统时间
// 上传技术
SmartUpload up = new SmartUpload()
// 进行初始化
up.initialize(this.getServletConfig(), request, response)
// 开始上传
try {
up.upload("utf-8")//设置编码方式。
int id = Integer.parseInt(up.getRequest().getParameter("id"))// 商品编号
SmartFiles sf = up.getFiles()// 得到上传的所有图片
SmartFile file = sf.getFile(0)// 根据索引得到上传图片 多个图片可以用循环:
String type = file.getFileExt()// 得到图片后缀名
String folder = "tp/"// 指定文件夹
String path = folder + time + "." + type// 路径
System.out.println(path + "路径")
file.saveAs(request.getRealPath("/") + path)// 保存图片
} catch (Exception e) {
e.printStackTrace()
}
//你搞个邮箱我把SmartUploadjar包 发给你吧。 //设置from提交
/*<form action="SellerServet" method="post"
enctype="multipart/form-data">*/ // 加上 enctype="multipart/form-data
<form action="pages/news/NewsServlet?status=insert" method="post" enctype="multipart/form-data">新闻图片:
<input type="file" name="img">
<br />
<input type="submit" value="添加">
</form>
后台代码
public void insert(HttpServletRequest request, HttpServletResponse response)
throws Exception {
SmartUpload smart = new SmartUpload()
smart.initialize(super.getServletConfig(), request, response)
smart.upload()
File img = smart.getFiles().getFile(0)
String fileName = null
if (img != null &&img.getSize() >0) {
fileName = UUID.randomUUID().toString() + "." + img.getFileExt()
img.saveAs("/upload/" + fileName)
}
String title = smart.getRequest().getParameter("title")
String content = smart.getRequest().getParameter("content")
News news = new News()
news.setTitle(title)
news.setContent(content)
news.setImg(fileName)
news.setPostDate(new Date())
boolean flag = ServiceFactory.getINewsServiceInstance().insert(news)
if (flag) {
request.setAttribute("message", "新闻添加成功")
} else {
request.setAttribute("message", "新闻添加失败")
}
request.setAttribute("url", "pages/news/NewsServlet?status=list")
request.getRequestDispatcher("/pages/forward.jsp").forward(request,
response)
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)