1 private String treatFile(File file, int type,
2 Remotecertapply remotecertapply)//要上传的对象
3 {
4 if (file == null)
5 return "图片文件为空";
6 if (file.length() > FILEMAXSIZE)
7 return "图片文件过大";
8
9 //输入流
10 InputStream is = null;
11
12 //输出流
13 OutputStream os = null;
14 try
15 {
16 String ext;
17 is = new FileInputStream(file);
18
19 //得到文件类型
20 FileType fileType = FileTypeJudge.getType(is);
21
22 //判断文件格式
23 if (FileType.JPEG.equals(fileType))
24 ext = ".jpg";
25 else if (FileType.PNG.equals(fileType))
26 ext = ".png";
27 else
28 ext = "图片文件不是JPG/PNG格式";
29 if (!ext.equals(".jpg") && !ext.equals(".png"))
30 return ext;
31 // 获取ServletAction上下文对象,getServletContext()获取Servlet上下文对象,getRealPath("upload")获取upload的绝对路径
32 String root = ServletActionContext.getServletContext()
33 .getRealPath("/remoteuserimages");
34
35 //获得文件名
36 String fileName = user.getId() + "_" + type
37 + System.currentTimeMillis() + ext;
38
39 //定义了一个byte类型的数组,数组长度为1024,buffer,有利于较少内存碎片,超过这个值就会报溢出的异常
40 byte[] buffer = new byte[1024];
41 int length = 0;
42
43 //关闭输入流
44 is.close();
45 is = new FileInputStream(file);
46 os = new FileOutputStream(new File(root, fileName));
47
48 //循环读取文件
49 while (-1 != (length = is.read(buffer, 0, buffer.length)))
50 os.write(buffer, 0, length);
51 //存储上传的文件
52 if (type == 1)
53 remotecertapply.setOrgnaid_imagepath(fileName);
54 else if (type == 2)
55 remotecertapply.setBusinessid_imagepath(fileName);
56 else if (type == 3)
57 remotecertapply.setTaxno_imagepath(fileName);
58 else
59 {
60 remotecertapply.setPersonid_imagepath(fileName);
61 remotecertapply.setIdtype(0);
62 }
63
64 return null;
65 }
66 catch (IOException e)
67 {
68 e.printStackTrace();
69 return "图片文件处理时发生IO错误";
70 }
71 finally
72 {
73 if (is != null)
74 try
75 {
76 is.close();
77 }
78 catch (IOException e)
79 {
80 }
81 if (os != null)
82 try
83 {
84 os.close();
85 }
86 catch (IOException e)
87 {
88 }
89 }
90 }