1. 程式人生 > >jsp+servlet上傳多張圖片向資料庫儲存名稱

jsp+servlet上傳多張圖片向資料庫儲存名稱

#jsp

<tr>
<td align="right">保修卡照片:</td>
<td ><input type="file" height="20px" name="image" id="image"/></td>
<td align="right">保修卡NVM表:</td>
<td><input type="file" name="photo" id="photo"/></td>
</tr>
<tr>
<td align="right">機器照片:</td>
<td><input type="file" name="picture" id="picture"/></td>
<td align="right">登記日期:</td>
<td><input type="date" name="regtime"   id="rgtime"/></td>
</tr>
<tr>
<td></td>
<td align="right"><input type="submit" value="新增" /></td>
<td><input type="reset" value="重置"></td>

#dao層

public void addMachine(Machine machine) throws SQLException{
QueryRunner qr=new QueryRunner(C3P0Util.getDataSource());
qr.update("insert into machine_t(id,number,name,model,offer,buytime," +
"company,owner,tel,addr,category,image,photo,picture," +
"regtime) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",machine.getId(),machine.getNumber(),
machine.getName(),machine.getModel(),machine.getOffer(),machine.getBuytime(),
machine.getCompany(),machine.getOwner(),machine.getTel(),machine.getAddr(),
machine.getCategory(),machine.getImage(),machine.getPhoto(),machine.getPicture(),machine.getRegtime());

}

#service層

public class MachineServiceImpl implements MachineService {
MachineDao machineDao=new MachineDaoImpl();
public void add(Machine machine) throws SQLException {
machineDao.addMachine(machine);

}

}

#建立一個可以呼叫的until工具類

public static Machine upload2(HttpServletRequest request,String uploadPath){

//Machine  表單實體類
try {
Machine machine =new Machine();
ConvertUtils.register(new DateLocaleConverter(), Date.class);//日期轉換器
BeanUtils.populate(machine, request.getParameterMap());
DiskFileItemFactory factory = new DiskFileItemFactory();//建立一個工廠物件
ServletFileUpload upload = new ServletFileUpload(factory);//建立一個檔案上傳解析器

upload.setHeaderEncoding("UTF-8"); //解決上傳檔案亂碼問題
 if(!ServletFileUpload.isMultipartContent(request)){
 return  machine;
 }
 List<FileItem> list = upload.parseRequest(request);
 for(FileItem item : list){
 if(item.isFormField()){//如果是普通表單文字
 String name = item.getFieldName();
 String value = item.getString("UTF-8");
//  System.out.println(name + "=" + value);
 BeanUtils.setProperty(machine, name, value);//封裝普通表單文字
 }else{
 String filename=item.getFieldName();//獲取上傳檔案的屬性名
 String filedName=item.getName();//獲取上傳檔案的名稱
 String fileName="";
 String fileName1="";

 String fileName2="";

                                         String savepath = uploadPath;//上傳的路徑 

                     //String savePath = this.getServletContext().getRealPath("/upload");

                                              if(filename.equals("image")){

 filedName=item.getName();
 if(filename!=null&&!filedName.equals("")){

  //針對不同瀏覽器上傳格式不同,只保留上傳檔案的名稱部分,並且為了防止檔名稱相同被覆蓋,賦予一個隨機id            

           filedName=UUID.randomUUID().toString()+filedName.substring(filedName.lastIndexOf("\\")+1);

 fileName=filedName;
//      System.out.println(fileName);
 machine.setImage(fileName);//存入資料庫  ps:這裡只向資料庫儲存檔名稱
 }
 }else if(filename.equals("photo")){
 filedName=item.getName();
 if(filename!=null&&!filedName.equals("")){
                             filedName=UUID.randomUUID().toString()+filedName.substring(filedName.lastIndexOf("\\")+1);
 fileName1=filedName;
//  System.out.println(fileName1);
 machine.setPhoto(fileName1);


 }
 }else if(filename.equals("picture")){
 filedName=item.getName();
 if(filename!=null&&!filedName.equals("")){
                             filedName=UUID.randomUUID().toString()+filedName.substring(filedName.lastIndexOf("\\")+1);
 fileName2=filedName;
//  System.out.println(fileName2);
 machine.setPicture(fileName2);
 }
 }
//  System.out.println(filename+"="+filedName);
 if(filedName==null || filedName.trim().equals("")){
 continue;
 }
 InputStream in = item.getInputStream();//建立一個輸入流
 FileOutputStream out = new FileOutputStream(savepath + "\\" + filedName);//建立一個輸出流
 byte buffer[] = new byte[1024];//建立一個緩衝區
 int len = 0;

 while((len=in.read(buffer))>0){

//使用FileOutputStream輸出流將緩衝區的資料寫入到指定的目錄(savepath + "\\" + filename)當中

 out.write(buffer, 0, len);
 }
 in.close();//關閉輸入流
 out.close();//關閉輸出流
 item.delete();//刪除臨時檔案
 }
 }
 return machine;
} catch (Exception e) {
e.printStackTrace();
}
return null;

}

#後臺servlet

public class MachineServlet extends HttpServlet {
private MachineService service =new MachineServiceImpl();

     private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");

try {

Machine machine =WebUtils.upload2(request, this.getServletContext().getRealPath("/images"));
machine.setId(UUID.randomUUID().toString());//給表單生成一個隨機id 注:資料庫使用自增的可去掉這一句
service.add(machine);
request.setAttribute("message", "新增成功!!");
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("message", "新增失敗!!");
}
request.getRequestDispatcher("/message.jsp").forward(request, response);

}


public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);

}

}