package com.sxt.servlet;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import com.sxt.bean.Goods;
import com.sxt.dao.GoodsDao;
import com.sxt.dao.impl.GoodsDaoImpl;
public class SaveGoodsServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 创建一个文件form表达存储数据的map
Map<String, String> map = new HashMap<String, String>();
// 获取上传文件类型
if (ServletFileUpload.isMultipartContent(request)) {
// 创建ServletFileUpload实例
ServletFileUpload fileUpload = new ServletFileUpload();
try {
// 解析request请求 返回FileItemStream的iterator实例
FileItemIterator iter = fileUpload.getItemIterator(request);
InputStream is = null;// 输出流
// 迭代取出
while (iter.hasNext()) {
FileItemStream item = iter.next();// 获取文件流
String name = item.getFieldName();// 返回表单中标签的name值
is = item.openStream();// 得到对应表单的输出流
if (item.isFormField()) {// 如果是非文件域,设置进入map,这里要注意多值处理
String value = Streams.asString(is,"UTF-8");
map.put(name, value); // 如果不是文件上传,处理
} else {
if (is.available() > 0) {// 如果输出流的内容大于0
String fname = item.getName();// 获取文件名
// 修改这个名字不能产生覆盖问题 时间戳
int a = (int) (Math.random() * 100);
long l = new Date().getTime();
fname = String.valueOf(l) + a + fname;
map.put("gurl", "upload/" + fname);
String path = request.getServletContext().getRealPath("/")+ "upload/" + fname;
Streams.copy(is, new FileOutputStream(path), true);// 拷贝内容到上传路径
}
}
}
} catch (FileUploadException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
GoodsDao dao = new GoodsDaoImpl();
String gid = map.get("gid");
Integer gi = null;
if(gid!=null && !gid.equals("")){
gi = Integer.valueOf(gid);
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
PrintWriter out = response.getWriter();
try {
Date d = sdf.parse(map.get("prodate"));
Timestamp t = new Timestamp(d.getTime());
Goods g = new Goods(gi, map.get("gname"), Double.parseDouble(map.get("gprice")), Integer.valueOf(map.get("gnum")),t, map.get("gaddr"), map.get("gtel"), Integer.valueOf(map.get("gstatus")), map.get("gurl"));
boolean b = dao.saveGoods(g);
if(b){
out.print(1);
}else{
out.print(0);
}
} catch (Exception e) {
e.printStackTrace();
}
out.close();
}
}