记录功能已经完成,实现参数+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 @Override 119 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 @Override 142 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 //OKHttp 157 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 @Override 212 public void onFailure(@NotNull Call call, @NotNull IOException e) { 213 Log.i("TRYxxx","连接失败"); 214 e.printstacktrace(); 215 } 216 217 @Override 218 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 @Override 243 public boolean setViewValue(View view, Object data, 244 String textRepresentation) { 245 // Todo Auto-generated method stub 246 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转file 258 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 @Override 333 public void camera() { 334 // Todo Auto-generated method stub 335 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 @Override 343 public void gallery() { 344 // Todo Auto-generated method stub 345 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 @Override 352 public void cancel() { 353 // Todo Auto-generated method stub 354 dialog.cancel(); 355 } 356 357 @Override 358 protected void onActivityResult(int requestCode, int resultCode, Intent data) { 359 // Todo Auto-generated method stub 360 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 @Override 391 public boolean setViewValue(View view, Object data, 392 String textRepresentation) { 393 // Todo Auto-generated method stub 394 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 @Override 417 protected void onResume() { 418 // Todo Auto-generated method stub 419 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 @Override 434 public boolean setViewValue(View view, Object data, 435 String textRepresentation) { 436 // Todo Auto-generated method stub 437 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 @Override 455 public void onItemClick(AdapterView<?> parent, View v, int position, long id) { 456 // Todo Auto-generated method stub 457 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 @Override 480 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 @Override 488 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 <LinearLayout 11 android:layout_width="wrap_content" 12 android:layout_height="wrap_content" 13 android:orientation="horizontal"> 14 15 <LinearLayout 16 android:layout_width="wrap_content" 17 android:layout_height="wrap_content" 18 android:orientation="vertical"> 19 20 <EditText 21 android:id="@+id/title" 22 android:layout_width="300dp" 23 android:layout_height="wrap_content" 24 android:hint="请输入标题"></EditText> 25 26 <EditText 27 android:id="@+id/kemu" 28 android:layout_width="150dp" 29 android:layout_height="wrap_content" 30 android:hint="学科/关键字" 31 ></EditText> 32 33 </LinearLayout> 34 <RadioGroup 35 android:id="@+id/rg" 36 android:layout_width="wrap_content" 37 android:layout_height="wrap_content" 38 android:layout_marginLeft="25dp" 39 > 40 <RadioButton 41 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 <RadioButton 49 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 <EditText 61 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.MyGridView 73 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 <Button 87 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 }
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 block 28 e.printstacktrace(); 29 } 30 } 31 if (a > 0) { 32 //返回为真 33 res = true; 34 } 35 //返回为假 36 return res; 37 } 38 39 }
总结:
写这个”记录“功能我新学了很多东西,包括图片选择回显,OKHttp等,本来这个任务可以提早完成的,奈何上一周状态实在不佳,对编写代码有许些抵触,然而我们的项目还有很多没有写完,我不能因此直接怠惰下去,这次记录功能画上了一个句号,我也需要调整心态,将这次的工作作为一个教训,要时刻提醒自己不能松懈。