KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > dlog4j > action > DlogUploadAction


1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 2 of the License, or
5  * (at your option) any later version.
6  *
7  * This program is distributed in the hope that it will be useful,
8  * but WITHOUT ANY WARRANTY; without even the implied warranty of
9  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  * GNU Library General Public License for more details.
11  *
12  * You should have received a copy of the GNU General Public License
13  * along with this program; if not, write to the Free Software
14  * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
15  */

16 package dlog4j.action;
17
18 import java.awt.image.BufferedImage JavaDoc;
19 import java.io.File JavaDoc;
20 import java.io.FileOutputStream JavaDoc;
21 import java.text.SimpleDateFormat JavaDoc;
22 import java.util.Date JavaDoc;
23
24 import javax.imageio.ImageIO JavaDoc;
25 import javax.servlet.http.HttpServletRequest JavaDoc;
26 import javax.servlet.http.HttpServletResponse JavaDoc;
27
28
29 import org.apache.commons.lang.StringUtils;
30 import org.apache.struts.action.ActionForm;
31 import org.apache.struts.action.ActionForward;
32 import org.apache.struts.action.ActionMapping;
33 import org.apache.struts.upload.FormFile;
34
35 import dlog4j.formbean.UploadFlashForm;
36 import dlog4j.formbean.UploadImageForm;
37
38 /**
39  * 日记附件上传
40  *
41  * @author Liudong
42  */

43 public class DlogUploadAction extends DlogActionBase {
44
45     // --------------------------------------------------------- Instance Variables
46
public final static String JavaDoc UPLOADDIR_KEY = "uploadDir";
47     public final static String JavaDoc FILEPATH_KEY = "filePath";
48     public final static String JavaDoc IMAGESTRING_KEY = "imageString";
49     static String JavaDoc uploadDir = null;
50     static String JavaDoc dirName = null;
51     
52     // --------------------------------------------------------- Methods
53
/**
54      * 上传图片
55      * @param mapping
56      * @param form
57      * @param request
58      * @param response
59      * @return
60      * @throws Exception
61      */

62     public ActionForward uploadImage(ActionMapping mapping, UploadImageForm form,
63             HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
64             throws Exception JavaDoc {
65         FormFile picture = form.getUploadFile();
66         String JavaDoc fn = getUniqueFileName(getFileExtendName(picture.getFileName()));
67         StringBuffer JavaDoc imgPath = new StringBuffer JavaDoc(uploadDir);
68         imgPath.append(File.separator);
69         imgPath.append(fn);
70         File JavaDoc imgFile = new File JavaDoc(imgPath.toString());
71         FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(imgFile);
72         try {
73             //写入到目录
74
fos.write(picture.getFileData());
75         } finally {
76             fos.close();
77         }
78         
79         //计算图像的大小
80
int width = 0, height=0;
81         try{
82             BufferedImage JavaDoc bi = ImageIO.read(imgFile);
83             width = bi.getWidth();
84             height = bi.getHeight();
85         }catch(Exception JavaDoc e){
86             getServlet().log("uploadImage process image failed.",e);
87         }
88         String JavaDoc img = dirName+'/'+fn;
89         request.setAttribute(FILEPATH_KEY,img);
90         StringBuffer JavaDoc imgstr = new StringBuffer JavaDoc(128);
91         imgstr.append("<img SRC='");
92         imgstr.append(img);
93         imgstr.append("'");
94         if(StringUtils.isNotEmpty(form.getTxtAlign())) {
95             imgstr.append(" align='");
96             imgstr.append(form.getTxtAlign());
97             imgstr.append("'");
98         }
99         if(StringUtils.isNotEmpty(form.getTxtBorder())) {
100             imgstr.append(" border='");
101             imgstr.append(form.getTxtBorder());
102             imgstr.append("'");
103         }
104         if(StringUtils.isNotEmpty(form.getDisplayText())) {
105             imgstr.append(" alt='");
106             imgstr.append(form.getDisplayText());
107             imgstr.append("'");
108         }
109         boolean sizeok = false;
110         if(width > 600 || StringUtils.isNotEmpty(form.getTxtWidth())) {
111             imgstr.append(" width='");
112             int nWidth = getValue(600,form.getTxtWidth());
113             imgstr.append(nWidth);
114             imgstr.append("'");
115             if(nWidth==600){
116                 int nHeight = (nWidth * height)/ width;
117                 imgstr.append(" height='");
118                 imgstr.append(nHeight);
119                 imgstr.append("'");
120                 sizeok = true;
121                 request.setAttribute("width",String.valueOf(nWidth));
122                 request.setAttribute("height",String.valueOf(nHeight));
123             }
124         }
125         if(!sizeok && (height > 450 || StringUtils.isNotEmpty(form.getTxtHeight()))) {
126             imgstr.append(" height='");
127             int nHeight = getValue(450,form.getTxtHeight());
128             imgstr.append(nHeight);
129             imgstr.append("'");
130             if(nHeight==450){
131                 int nWidth = (nHeight * width) / height;
132                 imgstr.append(" width='");
133                 imgstr.append(nWidth);
134                 imgstr.append("'");
135                 request.setAttribute("width",String.valueOf(nWidth));
136                 request.setAttribute("height",String.valueOf(nHeight));
137             }
138         }
139         imgstr.append("/>");
140         request.setAttribute(IMAGESTRING_KEY,imgstr.toString());
141         return mapping.getInputForward();
142     }
143     
144     protected int getValue(int pvalue, String JavaDoc rvalue){
145         int rv = Integer.MAX_VALUE;
146         try{
147             rv = Integer.parseInt(rvalue);
148         }catch(Exception JavaDoc e){}
149         return Math.min(pvalue, rv);
150     }
151     /**
152      * 上传flash
153      * @param mapping
154      * @param form
155      * @param request
156      * @param response
157      * @return
158      * @throws Exception
159      */

160     public ActionForward uploadFlash(ActionMapping mapping, UploadFlashForm form,
161             HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
162             throws Exception JavaDoc {
163         FormFile picture = form.getUploadFile();
164         String JavaDoc fn = getUniqueFileName(getFileExtendName(picture.getFileName()));
165         FileOutputStream JavaDoc fos = new FileOutputStream JavaDoc(uploadDir + File.separator + fn);
166         try {
167             //写入到目录
168
fos.write(picture.getFileData());
169             String JavaDoc flash = dirName+'/'+fn;
170             request.setAttribute(FILEPATH_KEY,flash);
171         } finally {
172             fos.close();
173         }
174         return mapping.getInputForward();
175     }
176     /**
177      * 附件上传
178      */

179     public ActionForward doDefault(ActionMapping mapping, ActionForm form,
180             HttpServletRequest JavaDoc request, HttpServletResponse JavaDoc response)
181             throws Exception JavaDoc {
182         if (uploadDir == null)
183             uploadDir = getUploadDir();
184         if(form instanceof UploadImageForm)
185             return uploadImage(mapping,(UploadImageForm)form,request,response);
186         if(form instanceof UploadFlashForm)
187             return uploadFlash(mapping,(UploadFlashForm)form,request,response);
188         return mapping.getInputForward();
189     }
190     /**
191      * 获取上传文件保存的目录全路径
192      * @return
193      */

194     protected String JavaDoc getUploadDir() {
195         if(dirName==null) {
196             dirName = servlet.getInitParameter(UPLOADDIR_KEY);
197             if (dirName == null)
198                 dirName = "uploads";
199         }
200         String JavaDoc webpath = servlet.getServletContext().getRealPath(dirName);
201         if (webpath.endsWith(File.separator))
202             webpath += File.separator;
203         return webpath;
204     }
205     /**
206      * 得到一个唯一的文件名
207      * @param extName
208      * @return
209      */

210     protected String JavaDoc getUniqueFileName(String JavaDoc extName) {
211         final SimpleDateFormat JavaDoc sdf =
212             new SimpleDateFormat JavaDoc("yyyyMMddhhmmssSSSS.");
213         String JavaDoc fn = null;
214         do {
215             fn = sdf.format(new Date JavaDoc()) + extName;
216             if (new File JavaDoc(uploadDir + fn).exists())
217                 continue;
218             break;
219         } while (true);
220         return fn;
221     }
222     /**
223      * 获取文件的扩展名
224      * @param file
225      * @return
226      */

227     protected static String JavaDoc getFileExtendName(String JavaDoc file) {
228         int idx = file.lastIndexOf('.');
229         return (idx == -1 || idx == (file.length() - 1))
230             ? ""
231             : file.substring(idx + 1).toLowerCase();
232     }
233     
234     public static void main(String JavaDoc[] args){
235         String JavaDoc str = null;
236         System.out.println(StringUtils.isEmpty(str));
237     }
238
239 }
240
Popular Tags