团队开发冲刺日(十四)

团队开发冲刺日(十四),第1张

概述记录功能已经完成,实现参数+txt文件+图片文件的提交,servlet接收并将文件路径存储入库,我们目前决定存储文件的方式是存储其路径,当然这份代码没有连接服务器,我是拿本地试的。先看一下效果截图:            接下来看看代码:Android端:【主要功能实现】Mai

  记录功能已经完成,实现参数+txt文件+图片文件的提交,servlet接收并将文件路径存储入库,我们目前决定存储文件的方式是存储其路径,当然这份代码没有连接服务器,我是拿本地试的。先看一下效果截图:

 

 

 

 

 

 

 

 

 

 

 

 接下来看看代码:

AndroID端:

【主要功能实现】MainActivity.java:

  1 package com.example.toa;  2   3 import java.io.ByteArrayOutputStream;  4 import java.io.file;  5 import java.io.fileNotFoundException;  6 import java.io.fileOutputStream;  7 import java.io.IOException;  8 import java.io.RandomAccessfile;  9 import java.text.SimpleDateFormat; 10 import java.util.ArrayList; 11 import java.util.Date; 12 import java.util.HashMap; 13 import java.util.Set; 14  15 import androID.annotation.Suppresslint; 16 import androID.app.Activity; 17 import androID.app.AlertDialog; 18 import androID.app.AlertDialog.Builder; 19 import androID.content.DialogInterface; 20 import androID.content.Intent; 21 import androID.content.pm.ActivityInfo; 22 import androID.graphics.Bitmap; 23 import androID.graphics.BitmapFactory; 24 import androID.net.Uri; 25 import androID.os.Bundle; 26 import androID.os.Environment; 27 import androID.provIDer.MediaStore; 28 import androID.text.TextUtils; 29 import androID.util.Log; 30 import androID.vIEw.LayoutInflater; 31 import androID.vIEw.VIEw; 32 import androID.vIEw.Window; 33 import androID.vIEw.WindowManager; 34 import androID.Widget.AdapterVIEw; 35 import androID.Widget.AdapterVIEw.OnItemClickListener; 36 import androID.Widget.button; 37 import androID.Widget.EditText; 38 import androID.Widget.GrIDVIEw; 39 import androID.Widget.ImageVIEw; 40 import androID.Widget.RadioGroup; 41 import androID.Widget.SimpleAdapter; 42 import androID.Widget.SimpleAdapter.VIEwBinder; 43 import androID.Widget.Toast; 44  45 import org.jetbrains.annotations.NotNull; 46  47 import okhttp3.Call; 48 import okhttp3.Callback; 49 import okhttp3.MediaType; 50 import okhttp3.Multipartbody; 51 import okhttp3.OkhttpClIEnt; 52 import okhttp3.Request; 53 import okhttp3.Requestbody; 54 import okhttp3.Response; 55  56  57 public class MainActivity extends Activity implements 58         MyDialog.OnbuttonClickListener, OnItemClickListener{ 59     private MyDialog dialog;// 图片选择对话框 60     public static final int NONE = 0; 61     public static final int PHOTOHRAPH = 1;// 拍照 62     public static final int PHOTOZOOM = 2; // 缩放 63     public static final int PHOTORESOulT = 3;// 结果 64     public static final String IMAGE_UnspecIFIED = "image/*"; 65     public static final MediaType PNG = MediaType.parse("image/png"); 66  67     private GrIDVIEw grIDVIEw; // 网格显示缩略图 68     private final int IMAGE_OPEN = 4; // 打开图片标记 69     private String pathImage; // 选择图片路径 70     private Bitmap bmp; // 导入临时图片 71     private ArrayList<HashMap<String, Bitmap>> imageItem; 72     private SimpleAdapter simpleAdapter; // 适配器 73     private EditText note; // 笔记文本 74     private EditText Title; // 标题文本 75     private EditText kemu; //学科 76     private button handin; // 上传按钮 77     private RadioGroup rg; // 单选按钮组 78     private boolean judge; // 判定公开/私有 79  80     @Suppresslint("SourceLockedOrIEntationActivity") 81     @OverrIDe 82     protected voID onCreate(Bundle savedInstanceState) { 83         super.onCreate(savedInstanceState); 84         requestwindowFeature(Window.FEATURE_NO_Title); 85         /* 86          * 防止键盘挡住输入框 不希望遮挡设置activity属性 androID:windowsoftinputMode="adjustPan" 87          * 希望动态调整高度 androID:windowsoftinputMode="adjustResize" 88          */ 89         getwindow().setSoftinputMode( 90                 WindowManager.LayoutParams.soFT_input_ADJUST_PAN); 91         // 锁定屏幕 92         setRequestedOrIEntation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); 93         setContentVIEw(R.layout.activity_main); 94         //点击事件 95         init(); 96         //加载图片与回显 97         initData(); 98     } 99 100     private voID init() {101         //声明102         note = (EditText)findVIEwByID(R.ID.note);103         grIDVIEw = (GrIDVIEw) findVIEwByID(R.ID.grIDVIEw);104         handin = (button)findVIEwByID(R.ID.handin);105         Title = (EditText)findVIEwByID(R.ID.Title);106         kemu = (EditText)findVIEwByID(R.ID.kemu);107         rg = (RadioGroup)findVIEwByID(R.ID.rg);108         note.setHorizontallyScrolling(true);109         grIDVIEw.setonItemClickListener(this);110         dialog = new MyDialog(this);111         dialog.setonbuttonClickListener(this);112         // activity中调用其他activity中组件的方法113         LayoutInflater layout = this.getLayoutInflater();114         VIEw vIEw = layout.inflate(R.layout.layout_select_photo, null);115 116         //单选按钮(公开/私有)117         rg.setonCheckedchangelistener(new RadioGroup.OnCheckedchangelistener() {118             @OverrIDe119             public voID onCheckedChanged(RadioGroup group, int checkedID) {120                 if(checkedID == R.ID.ok){121                     judge = true;122                 }else{123                     judge = false;124                 }125             }126         });127 128         handin.setonClickListener(new VIEw.OnClickListener() {129             //是否公开130             private String see_str = "";131             //正文132             private String note_str = "";133             //标题134             private String Title_str = "";135             //用户名(登录界面传参获取)136             private String user_str = "try";137             //学科138             private  String kemu_str = "";139             //年级(传参获取)140             private String year_str = "3";141             @OverrIDe142             public voID onClick(VIEw v) {143                 if(judge){144                     see_str = "公开";145                 }else{146                     see_str = "私有";147                 }148                 note_str = note.getText().toString();149                 Title_str = Title.getText().toString();150                 kemu_str = kemu.getText().toString();151 152                 //本地Tomcat,注意不能写localhost,写本机的ip地址【连接服务器时记得改地址】153                 String URL="http://192.168.101.18:8080/CloudNote/CloudServlet";154                 //URL携带部分参数155                 URL+="?title="+Title_str+"&see="+see_str+"&user="+user_str+"&kemu="+kemu_str+"&year="+year_str;156                 //OKhttp157                 OkhttpClIEnt clIEnt = new OkhttpClIEnt();158                 Multipartbody.Builder builder = new Multipartbody.Builder().setType(Multipartbody.ALTERNATIVE);159                 //文本文件160                 MediaType NoteType = MediaType.parse("text/HTML;charset=utf-8");161                 //设置文件命名前缀部分162                 String noteuser = user_str+"_note";163                 file Notefile = doString(note_str,noteuser);164                 builder.addFormDataPart("note",Notefile.getname(),Requestbody.create(NoteType,Notefile));165 166                 //图片文件,设定最多上传3张,不包括+号图片。167                 int pic_i=0;168                 for(HashMap<String,Bitmap>pic:imageItem){169                     Set<String> set=pic.keySet();170                     for(String key:set){171                         if(pic_i==0){172                             //跳过默认的+号图片173                             pic_i++;174                             continue;175                         }176                         //取出bitmap,转换成file,上传177                         else if(pic_i==1){178                             Bitmap fbm1 = pic.get(key);179                             //设置文件命名前缀部分180                             String image1user = user_str+"_image1";181                             //调用方法生成图片文件182                             file dofile = doImage(fbm1,image1user);183                             builder.addFormDataPart("image1",dofile.getname(),Requestbody.create(PNG,dofile));184                             pic_i++;185                         }186                         else if(pic_i==2){187                             Bitmap fbm2 = pic.get(key);188                             //设置文件命名前缀部分189                             String image2user = user_str+"_image2";190                             //调用方法生成图片文件191                             file dofile = doImage(fbm2,image2user);192                             builder.addFormDataPart("image2",dofile.getname(),Requestbody.create(PNG,dofile));193                             pic_i++;194                         }195                         else if(pic_i==3){196                             Bitmap fbm3 = pic.get(key);197                             //设置文件命名前缀部分198                             String image3user = user_str+"_image3";199                             //调用方法生成图片文件200                             file dofile = doImage(fbm3,image3user);201                             builder.addFormDataPart("image3",dofile.getname(),Requestbody.create(PNG,dofile));202                             pic_i++;203                         }204                     }205                 }206                 Requestbody requestbody = builder.build();207                 Request request = new Request.Builder().url(URL)208                         .post(requestbody)209                         .build();210                 clIEnt.newCall(request).enqueue(new Callback() {211                     @OverrIDe212                     public voID onFailure(@NotNull Call call, @NotNull IOException e) {213                         Log.i("TRYxxx","连接失败");214                         e.printstacktrace();215                     }216 217                     @OverrIDe218                     public voID onResponse(@NotNull Call call, @NotNull Response response) throws IOException {219                         Log.i("TRYxxx","连接的消息"+response.message());220                         if(response.isSuccessful()){221                             Log.i("TRYxxx","连接成功");222                         }223                     }224                 });225             }226         });227     }228     private voID initData() {229         /*230          * 载入默认图片添加图片加号231          */232         bmp = BitmapFactory.decodeResource(getResources(),233                 R.drawable.ic_addpic); // 加号234         imageItem = new ArrayList<HashMap<String, Bitmap>>();235         HashMap<String, Bitmap> map = new HashMap<String, Bitmap>();236         map.put("itemImage", bmp);237         imageItem.add(map);238         simpleAdapter = new SimpleAdapter(this, imageItem,239                 R.layout.grIDitem_addpic, new String[] { "itemImage" },240                 new int[] { R.ID.imageVIEw1 });241         simpleAdapter.setVIEwBinder(new VIEwBinder() {242             @OverrIDe243             public boolean setVIEwValue(VIEw vIEw, Object data,244                                         String textRepresentation) {245                 // Todo auto-generated method stub246                 if (vIEw instanceof ImageVIEw && data instanceof Bitmap) {247                     ImageVIEw i = (ImageVIEw) vIEw;248                     i.setimageBitmap((Bitmap) data);249                     return true;250                 }251                 return false;252             }253         });254         grIDVIEw.setAdapter(simpleAdapter);255     }256 257     //Bitmap转file258     public static file doImage(Bitmap fbitmap, String user) {259         ByteArrayOutputStream fbaos = new ByteArrayOutputStream();260         fbitmap.compress(Bitmap.CompressFormat.JPEG,100,fbaos);261         int options = 100;262         //判断是否大于20kb,是则继续压缩263         while(fbaos.toByteArray().length/1024>20){264             fbaos.reset();265             options-=10;266             fbitmap.compress(Bitmap.CompressFormat.JPEG,options,fbaos);267             long length = fbaos.toByteArray().length;268         }269         SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");270         Date date = new Date(System.currentTimeMillis());271         String filename = user+"_"+format.format(date);272         String filepath = Environment.getExternalStorageDirectory().toString()+"/CloudNoteImage";273         file pathfile = new file(filepath);274         if(!pathfile.exists()){275             pathfile.mkdir();276         }277         file file = new file(filepath,filename+".png");278         //注意创建文件,否则会发生文件读取错误279         if(!file.exists()){280             try{281                 file.createNewfile();282             }catch (IOException e){283                 e.printstacktrace();284             }285         }286         try{287             fileOutputStream fos = new fileOutputStream(file);288             try{289                 fos.write(fbaos.toByteArray());290                 fos.flush();291                 fos.close();292             } catch (IOException e) {293                 e.printstacktrace();294             }295         }catch (IOException e){296             e.printstacktrace();297         }298         return file;299     }300 301     //将正文信息写入txt文件302     public static file doString(String strwrite, String user){303         //取时间304         SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");305         Date date = new Date(System.currentTimeMillis());306         //生成文件名307         String filename = user+"_"+format.format(date);308         String filepath = Environment.getExternalStorageDirectory().toString()+"/CloudNoteTXT";309         //创建文件310         file pathfile = new file(filepath);311         if(!pathfile.exists()){312             pathfile.mkdir();313         }314         file file = new file(filepath,filename+".txt");315         if(!file.exists()){316             try{317                 file.createNewfile();318             }catch (IOException e){319                 e.printstacktrace();320             }321         }322         try{323             fileOutputStream outputStream = new fileOutputStream(file);324             outputStream.write(strwrite.getBytes());325             outputStream.close();326         } catch (IOException e) {327             e.printstacktrace();328         }329         return file;330     }331     //调用相机332     @OverrIDe333     public voID camera() {334         // Todo auto-generated method stub335         Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);336         intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromfile(new file(337                 Environment.getExternalStorageDirectory(), "temp.jpg")));338         startActivityForResult(intent, PHOTOHRAPH);339     }340 341     //调用相册342     @OverrIDe343     public voID gallery() {344         // Todo auto-generated method stub345         Intent intent = new Intent(Intent.ACTION_PICK,346                 androID.provIDer.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);347         startActivityForResult(intent, IMAGE_OPEN);348 349     }350 351     @OverrIDe352     public voID cancel() {353         // Todo auto-generated method stub354         dialog.cancel();355     }356 357     @OverrIDe358     protected voID onActivityResult(int requestCode, int resultCode, Intent data) {359         // Todo auto-generated method stub360         super.onActivityResult(requestCode, resultCode, data);361 362         if (resultCode == NONE)363             return;364         // 拍照365         if (requestCode == PHOTOHRAPH) {366             // 设置文件保存路径这里放在跟目录下367             file picture = new file(Environment.getExternalStorageDirectory()368                     + "/temp.jpg");369             startPhotoZoom(Uri.fromfile(picture));370         }371 372         if (data == null)373             return;374 375         // 处理结果376         if (requestCode == PHOTORESOulT) {377             Bundle extras = data.getExtras();378             if (extras != null) {379                 Bitmap photo = extras.getParcelable("data");380                 ByteArrayOutputStream stream = new ByteArrayOutputStream();381                 photo.compress(Bitmap.CompressFormat.JPEG, 75, stream);// (0-100)压缩文件382                 // 将图片放入grIDvIEw中383                 HashMap<String, Bitmap> map = new HashMap<String, Bitmap>();384                 map.put("itemImage", photo);385                 imageItem.add(map);386                 simpleAdapter = new SimpleAdapter(this, imageItem,387                         R.layout.grIDitem_addpic, new String[] { "itemImage" },388                         new int[] { R.ID.imageVIEw1 });389                 simpleAdapter.setVIEwBinder(new VIEwBinder() {390                     @OverrIDe391                     public boolean setVIEwValue(VIEw vIEw, Object data,392                                                 String textRepresentation) {393                         // Todo auto-generated method stub394                         if (vIEw instanceof ImageVIEw && data instanceof Bitmap) {395                             ImageVIEw i = (ImageVIEw) vIEw;396                             i.setimageBitmap((Bitmap) data);397                             return true;398                         }399                         return false;400                     }401                 });402                 grIDVIEw.setAdapter(simpleAdapter);403                 simpleAdapter.notifyDataSetChanged();404                 dialog.dismiss();405             }406 407         }408         // 打开图片409         if (resultCode == RESulT_OK && requestCode == IMAGE_OPEN) {410             startPhotoZoom(data.getData());411         }412         super.onActivityResult(requestCode, resultCode, data);413 414     }415 416     @OverrIDe417     protected voID onResume() {418         // Todo auto-generated method stub419         super.onResume();420         //判定有图片添加421         if (!TextUtils.isEmpty(pathImage)) {422             //bitmap回显423             Bitmap addbmp = BitmapFactory.decodefile(pathImage);424             //将信息存入Map中425             HashMap<String, Bitmap> map = new HashMap<String, Bitmap>();426             map.put("itemImage", addbmp);427             imageItem.add(map);428             //在grIDitem_addpic.xml中向imageVIEw1添加图片429             simpleAdapter = new SimpleAdapter(this, imageItem,430                     R.layout.grIDitem_addpic, new String[] { "itemImage" },431                     new int[] { R.ID.imageVIEw1 });432             simpleAdapter.setVIEwBinder(new VIEwBinder() {433                 @OverrIDe434                 public boolean setVIEwValue(VIEw vIEw, Object data,435                                             String textRepresentation) {436                     // Todo auto-generated method stub437                     if (vIEw instanceof ImageVIEw && data instanceof Bitmap) {438                         ImageVIEw i = (ImageVIEw) vIEw;439                         i.setimageBitmap((Bitmap) data);440                         return true;441                     }442                     return false;443                 }444             });445             grIDVIEw.setAdapter(simpleAdapter);446             simpleAdapter.notifyDataSetChanged();447             // 刷新后释放防止手机休眠后自动添加448             pathImage = null;449             dialog.dismiss();450         }451 452     }453 454     @OverrIDe455     public voID onItemClick(AdapterVIEw<?> parent, VIEw v, int position, long ID) {456         // Todo auto-generated method stub457         if (imageItem.size() == 4&&position==0) { // 第一张为默认图片,点击+号时才判定是否已满458             Toast.makeText(MainActivity.this, "图片数3张已满",459                     Toast.LENGTH_SHORT).show();460         } else if (position == 0) { // 点击图片位置为+ 0对应0张图片461             // 选择图片462             dialog.show();463 464             // 通过onResume()刷新数据465         } else {466             dialog(position);467         }468 469     }470 471     /*472      * Dialog对话框提示用户删除 *** 作 position为删除图片位置473      */474     protected voID dialog(final int position) {475         AlertDialog.Builder builder = new Builder(MainActivity.this);476         builder.setMessage("确认移除已添加图片吗?");477         builder.setTitle("提示");478         builder.setPositivebutton("确认", new DialogInterface.OnClickListener() {479             @OverrIDe480             public voID onClick(DialogInterface dialog, int which) {481                 dialog.dismiss();482                 imageItem.remove(position);483                 simpleAdapter.notifyDataSetChanged();484             }485         });486         builder.setNegativebutton("取消", new DialogInterface.OnClickListener() {487             @OverrIDe488             public voID onClick(DialogInterface dialog, int which) {489                 dialog.dismiss();490             }491         });492         builder.create().show();493     }494 495     public voID startPhotoZoom(Uri uri) {496         Intent intent = new Intent("com.androID.camera.action.CROP");497         intent.setDataAndType(uri, IMAGE_UnspecIFIED);498         intent.putExtra("crop", "true");499         // aspectX aspectY 是宽高的比例500         intent.putExtra("aspectX", 1);501         intent.putExtra("aspectY", 1);502         // outputX outputY 是裁剪图片宽高503         intent.putExtra("outputX", 64);504         intent.putExtra("outputY", 64);505         intent.putExtra("return-data", true);506         startActivityForResult(intent, PHOTORESOulT);507     }508 509 }

这里一些代码细节在之前的开发总结提到过了,这里不再多提。

其他后台代码如Dialog,GrIDVIEw参照我的冲刺日(四)博客,与原博主无异,感谢原博主的帮助。

主界面布局文件做出了一些改动,主要是增设了“学科/关键字”输入框,代码如下:

 1 <?xml version="1.0" enCoding="utf-8"?> 2 <linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID" 3     xmlns:app="http://schemas.androID.com/apk/res-auto" 4     xmlns:tools="http://schemas.androID.com/tools" 5     androID:layout_wIDth="match_parent" 6     androID:layout_height="match_parent" 7     androID:orIEntation="vertical" 8     tools:context=".MainActivity"> 9 10     <linearLayout11         androID:layout_wIDth="wrap_content"12         androID:layout_height="wrap_content"13         androID:orIEntation="horizontal">14 15         <linearLayout16             androID:layout_wIDth="wrap_content"17             androID:layout_height="wrap_content"18             androID:orIEntation="vertical">19 20             <EditText21                 androID:ID="@+ID/Title"22                 androID:layout_wIDth="300dp"23                 androID:layout_height="wrap_content"24                 androID:hint="请输入标题"></EditText>25 26             <EditText27                 androID:ID="@+ID/kemu"28                 androID:layout_wIDth="150dp"29                 androID:layout_height="wrap_content"30                 androID:hint="学科/关键字"31                 ></EditText>32 33         </linearLayout>34         <RadioGroup35             androID:ID="@+ID/rg"36             androID:layout_wIDth="wrap_content"37             androID:layout_height="wrap_content"38             androID:layout_marginleft="25dp"39             >40             <Radiobutton41                 androID:layout_wIDth="wrap_content"42                 androID:layout_height="wrap_content"43                 androID:ID="@+ID/ok"44                 androID:text="公开"45                 androID:checked="false"46                 >47             </Radiobutton>48             <Radiobutton49                 androID:layout_wIDth="wrap_content"50                 androID:layout_height="wrap_content"51                 androID:ID="@+ID/no"52                 androID:text="私有"53                 androID:checked="true"54                 >55             </Radiobutton>56         </RadioGroup>57 58     </linearLayout>59 60     <EditText61         androID:ID="@+ID/note"62         androID:layout_wIDth="match_parent"63         androID:layout_height="500dp"64         androID:gravity="top"65         androID:singleline="false"66         androID:inputType="textMultiline"67         androID:scrollbars="vertical"68         androID:maxlines="20"69         androID:hint="请输入正文"70         ></EditText>71 72     <com.example.toa.MyGrIDVIEw73         androID:ID="@+ID/grIDVIEw"74         androID:layout_wIDth="match_parent"75         androID:layout_height="wrap_content"76         androID:columnWIDth="90dp"77         androID:layout_margin="5dp"78         androID:layout_weight="111"79         androID:gravity="center"80         androID:horizontalSpacing="5dp"81         androID:numColumns="4"82         androID:scrollbars="none"83         androID:stretchMode="columnWIDth">84     </com.example.toa.MyGrIDVIEw>85 86     <button87         androID:ID="@+ID/handin"88         androID:layout_wIDth="match_parent"89         androID:layout_height="50dp"90         androID:text="上传"91         >92     </button>93 </linearLayout>

 

Servlet:

CloudServlet(接收文件和参数)【参考博客冲刺日(十三)】

  1 package Servlet;  2   3 import java.io.fileOutputStream;  4 import java.io.IOException;  5 import java.io.inputStream;  6 import java.io.OutputStream;  7 import java.util.List;  8   9 import javax.servlet.servletexception; 10 import javax.servlet.annotation.WebServlet; 11 import javax.servlet.http.httpServlet; 12 import javax.servlet.http.httpServletRequest; 13 import javax.servlet.http.httpServletResponse; 14  15 import org.apache.commons.fileupload.fileItem; 16 import org.apache.commons.fileupload.fileUploadException; 17 import org.apache.commons.fileupload.disk.diskfileItemFactory; 18 import org.apache.commons.fileupload.servlet.ServletfileUpload; 19  20 import Dao.InsertDao; 21  22 /** 23  * Servlet implementation class CloudServlet 24  */ 25 @WebServlet("/CloudServlet") 26 public class CloudServlet extends httpServlet { 27     private static final long serialVersionUID = 1L; 28         29     /** 30      * @see httpServlet#httpServlet() 31      */ 32     public CloudServlet() { 33         super(); 34         // Todo auto-generated constructor stub 35     } 36  37     /** 38      * @see httpServlet#doGet(httpServletRequest request, httpServletResponse response) 39      */ 40     protected voID doGet(httpServletRequest request, httpServletResponse response) throws servletexception, IOException { 41         // Todo auto-generated method stub 42         response.getWriter().append("Served at: ").append(request.getcontextpath()); 43     } 44  45     /** 46      * @see httpServlet#doPost(httpServletRequest request, httpServletResponse response) 47      */ 48     protected voID doPost(httpServletRequest request, httpServletResponse response) throws servletexception, IOException { 49         // Todo auto-generated method stub 50         request.setCharacterEnCoding("utf-8"); 51         response.setContentType("text/HTML;charset=utf-8;"); 52          53         //标题 54         String Title = request.getParameter("Title"); 55         //公开/私有 56         String see = request.getParameter("see"); 57         //用户名 58         String user = request.getParameter("user"); 59         //学科 60         String kemu = request.getParameter("kemu"); 61         //年级 62         String year = request.getParameter("year"); 63         //TXT文件路径(传参用) 64         String txtfile = null; 65         //图片文件1路径(传参用) 66         String image1file = null; 67         //图片文件2路径(传参用) 68         String image2file = null; 69         //图片文件3路径(传参用) 70         String image3file = null; 71          72         //图片存储文件夹【服务器端记得构建,这是本地的】 73         String imagepath = "E:/CloudNoteTry/Image"; 74         //笔记存储文件夹【服务器端记得构建,这是本地的】 75         String txtpath = "E:/CloudNoteTry/Note"; 76         diskfileItemFactory factory = new diskfileItemFactory(); 77         ServletfileUpload upload = new ServletfileUpload(factory); 78         List<fileItem>List; 79         //第1个文件是txt,234是图片文件 80         int point=1; 81         try { 82             List = upload.parseRequest(request); 83             for(fileItem item:List) { 84                 if(!item.isFormFIEld()) { 85                     String filename = item.getname(); 86                     int len = 0; 87                     byte buff[] = new byte[1024]; 88                     if(point == 1) { 89                         txtfile = txtpath+"/"+filename; 90                         inputStream inputStream = item.getinputStream(); 91                         OutputStream outputStream = new fileOutputStream(txtpath+"/"+filename); 92                         //读写文件内容 93                         while((len = inputStream.read(buff))!=-1) { 94                             outputStream.write(buff,0,len); 95                         } 96                         outputStream.flush(); 97                         outputStream.close(); 98                         inputStream.close(); 99                     }else {100                         if(point == 2) {101                             image1file = imagepath+"/"+filename;102                         }else if(point == 3) {103                             image2file = imagepath+"/"+filename;104                         }else if(point == 4) {105                             image3file = imagepath+"/"+filename;106                         }107                         inputStream inputStream = item.getinputStream();108                         OutputStream outputStream = new fileOutputStream(imagepath+"/"+filename);109                         //读写文件内容110                         while((len = inputStream.read(buff))!=-1) {111                             outputStream.write(buff,0,len);112                         }113                         outputStream.flush();114                         outputStream.close();115                         inputStream.close();116                     }117                     point++;118                 }119             }120         }catch(fileUploadException e) {121             e.printstacktrace();122         }123         //判定是否为null,否则可能会报错124         if(Title==null) {125             title="ERROR";126         }if(see==null) {127             see="ERROR";128         }if(user==null) {129             user="ERROR";130         }if(kemu==null) {131             kemu="ERROR";132         }if(year==null) {133             year="ERROR";134         }135         136         //声明Dao包内InsertDao对象,调用添加方法137         InsertDao ins = new InsertDao();138         //返回为boolean类型,根据结果判断是否成功139         if(ins.insertCN(user, year, kemu, Title, txtfile, image1file, image2file, image3file, see)) {140             System.out.println("添加成功");141         }else {142             System.out.println("添加失败");143         }144     }145 146 }

 

Dao层添加数据入库代码:InsertDao:

 1 package Dao; 2  3 import java.sql.Connection; 4 import java.sql.sqlException; 5 import java.sql.Statement; 6 import util.DBUtil; 7  8 public class InsertDao { 9     public boolean insertCN(String user,String year,String kemu,String Title,String note,String image1,String image2,String image3,String see) {10         boolean res = false;11         //添加语句,PYDcloud为表名12         String sql="insert into PYDcloud(user,nianji,kemu,Title,note,image1,image2,image3,SEE)"13                 +"values('"+user+"','"+year+"','"+kemu+"','"+Title+"','"+note+"','"+image1+"','"+image2+"','"+image3+"','"+see+"')";14         Connection conn = DBUtil.getConn();15         Statement state = null;16         int a = 0;17         try {18             state = conn.createStatement();19             //每执行一条语句,a++20             a = state.executeUpdate(sql);21         }catch (Exception e) {22             e.printstacktrace();23         }finally {24             try {25                 DBUtil.close(state, conn);26             } catch (sqlException e) {27                 // Todo auto-generated catch block28                 e.printstacktrace();29             }30         }31         if (a > 0) {32             //返回为真33             res = true;34         }35         //返回为假36         return res;37     }38 39 }

 

总结:

写这个”记录“功能我新学了很多东西,包括图片选择回显,OKhttp等,本来这个任务可以提早完成的,奈何上一周状态实在不佳,对编写代码有许些抵触,然而我们的项目还有很多没有写完,我不能因此直接怠惰下去,这次记录功能画上了一个句号,我也需要调整心态,将这次的工作作为一个教训,要时刻提醒自己不能松懈。

 

总结

以上是内存溢出为你收集整理的团队开发冲刺日(十四)全部内容,希望文章能够帮你解决团队开发冲刺日(十四)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1062251.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存