struts2.0利用注解上传和下载图片

action的代码:

  1 package cn.com.spdbccc.coms.action;
  2 
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.IOException;
  6 import java.io.InputStream;
  7 import java.io.UnsupportedEncodingException;
  8 import java.text.SimpleDateFormat;
  9 import java.util.Date;
 10 import org.apache.commons.io.FileUtils;
 11 import org.apache.commons.lang.xwork.StringUtils;
 12 import org.apache.commons.logging.Log;
 13 import org.apache.commons.logging.LogFactory;
 14 import org.apache.struts2.ServletActionContext;
 15 import org.apache.struts2.convention.annotation.InterceptorRef;
 16 import org.apache.struts2.convention.annotation.Result;
 17 import org.apache.struts2.convention.annotation.Results;
 18 import org.springframework.beans.factory.annotation.Autowired;
 19 import cn.com.spdbccc.coms.helper.MasterHelper;
 20 import cn.com.spdbccc.coms.model.CardBase;
 21 import cn.com.spdbccc.coms.model.User;
 22 import cn.com.spdbccc.coms.service.CardBaseService;
 23 import cn.com.spdbccc.coms.service.UniqueException;
 24 import cn.com.spdbccc.coms.util.BrowserEncodingUtils;
 25 
 26 import com.opensymphony.xwork2.Action;
 27 
 28 @InterceptorRef(value = "fileUpload", params = { "maximumSize", "5242880",
 29         "allowedExtensions", ".jpg", "allowedTypes", "image/jpeg"})
 30 @Results({
 31         @Result(name = Action.SUCCESS, type = "redirect", location = "card-base-list.action"),
 32         @Result(name = CardBaseAction.PICTURE, type = "stream", params = {
 33                 "contentType", "application/image/jpeg", "inputName",
 34                 "downloadedPictureStream", "contentDisposition",
 35                 "attachment;filename="${downloadedPictureName}"",
 36                 "bufferSize", "4096" }) })
 37 public class CardBaseAction extends
 38         AbstractCRUDAction<CardBase, Long, CardBaseService> {
 39     /**
 40      * serialVersionUID
 41      */
 42     public static final long serialVersionUID = 5015762234382684801L;
 43 
 44     private final static Log log = LogFactory.getLog(CardBaseAction.class);
 45     /**
 46      * 下载时的图片名
 47      */
 48     private String downloadedPictureName;
 49 
 50     private InputStream downloadedPictureStream;
 51     
 52     /**
 53      * 在页面显示的图片名
 54      */
 55     private String displayedPictureName;
 56 
 57     /**
 58      * 相对于服务器的图片所在路径
 59      */
 60     private String pictureWebPath;
 61 
 62     /**
 63      * @param cardBaseService
 64      *            the cardBaseService to set
 65      */
 66     @Autowired
 67     public void setCardBaseService(CardBaseService cardBaseService) {
 68         super.setService(cardBaseService);
 69     }
 70 
 71     @Override
 72     public String save() throws Exception {
 73         // 当文件过大或者文件类型不符合的时候,hasError在拦截器处已经为false。但是仍然能够跳转到该函数
 74         // 因此将hasError继承父类的值进行返回
 75         boolean hasError = super.hasErrors();
 76         if (!hasError) {
 77             User user = getUserFromSession();
 78             try {
 79                 if (model.getPicture() != null) {
 80                     model.setPicturePath(getSavedPicturePathName());
 81                 }
 82                 service.save(model, user.getId());
 83 
 84             } catch (UniqueException e) {
 85                 addActionError(getText("errors.card.base.name.unique",
 86                         new String[] { model.getName() }));
 87                 hasError = true;
 88             }
 89         }
 90 
 91         return hasError ? INPUT : SUCCESS;
 92     }
 93 
 94     @Override
 95     public String update() throws Exception {
 96         // 当文件过大或者文件类型不符合的时候,hasError在拦截器处已经为false。但是仍然能够跳转到该函数
 97         // 因此将hasError继承父类的值进行返回
 98         boolean hasError = super.hasErrors();
 99         if (!hasError) {
100             User user = getUserFromSession();
101             try {
102                 if (model.getPicture() != null) {
103                     model.setPicturePath(getSavedPicturePathName());
104                 }
105                 service.update(model, user.getId());
106             } catch (UniqueException e) {
107                 addActionError(getText("errors.card.base.name.unique",
108                         new String[] { model.getName() }));
109                 hasError = true;
110             } catch (Exception e) {
111                 log.error(e);
112                 addActionError(getText("errors.card.base.upload.failed",
113                         new String[] { model.getPicturePath() }));
114                 hasError = true;
115             }
116         }
117         return hasError ? INPUT : SUCCESS;
118     }
119 
120     public String download() throws Exception {
121         downloadedPictureStream = null;
122         boolean hasError = false;
123         try {
124             if (StringUtils.isNotEmpty(model.getPicturePath())) {
125                 model.setPicture(new File(model.getPicturePath()));
126                 if (model.getPicture().exists()) {
127                     downloadedPictureStream = new FileInputStream(model.getPicture());
128                 }
129             }
130         } catch (IOException e) {
131             log.error(e);
132             addActionError(getText("errors.card.base.download.failed",
133                     new String[] { getDisplayedPictureName() }));
134             hasError = true;
135         }
136         return hasError ? INPUT : PICTURE;
137         
138     }
139     
140     /**
141      * 保存图片并获取文件名和路径
142      * 
143      * @return
144      * @throws Exception
145      */
146     public String getSavedPicturePathName() throws Exception {
147         SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMddHHmmssSSS"); // 精确到毫秒
148         User user = getUserFromSession();
149         String savedPictureFileName = user.getId() + "_" + fmt.format(new Date()) + ".jpg";// 取文件名:用户id_时间(毫秒级)
150         File savedPicture = null;
151         try {
152             if (model.getPicture() != null) {
153                 String cardBasePath = MasterHelper.get().getValue("card.base.path");
154                 String savedPicturePath = ServletActionContext.getServletContext().getRealPath(cardBasePath);
155                 savedPicture = new File(savedPicturePath, savedPictureFileName);
156                 if (!savedPicture.getParentFile().exists()) {
157                     savedPicture.getParentFile().mkdirs();
158                 }
159                 FileUtils.copyFile(model.getPicture(), savedPicture);
160                 model.getPicture().delete();// 删除临时文件
161             }
162         } catch (Exception e) {
163             throw e;
164         }
165         return savedPicture.getAbsolutePath();// 获取的包括路径和名称
166     }
167     
168     public void setDownloadedPictureStream(InputStream downloadedPictureStream) {
169         this.downloadedPictureStream = downloadedPictureStream;
170     }
171 
172     
173 
174     public String deletePicture() throws Exception {
175         model.setPicturePath("");
176         super.update();
177         return INPUT;
178     }
179 
180     public InputStream getDownloadedPictureStream() {
181         return downloadedPictureStream;
182     }
183 
184     public String getPictureWebPath() throws Exception {
185         model.setPicture(new File(model.getPicturePath()));//通过PicturePath找到图片
186         //如果PicturePath存在,但是Picture不存在,就不显示,不用抛出异常
187         pictureWebPath = MasterHelper.get().getValue("card.base.path") + "/" + model.getPicture().getName();
188         return pictureWebPath;
189     }
190 
191     public void setPictureWebPath(String pictureWebPath) {
192         this.pictureWebPath = pictureWebPath;
193     }
194 
195     /**
196      * 获取下载的图片名
197      * 
198      * @return
199      * @throws UnsupportedEncodingException
200      */
201     public String getDownloadedPictureName() throws UnsupportedEncodingException {
202         // 处理浏览器中文文件名乱码问题
203         downloadedPictureName = BrowserEncodingUtils.convert(getDisplayedPictureName());
204         return downloadedPictureName;
205     }
206 
207     public void setDownloadedPictureName(String downloadedPictureName) {
208         this.downloadedPictureName = downloadedPictureName;
209     }
210 
211     public String getDisplayedPictureName() {
212         if (StringUtils.isNotEmpty(model.getCardBaseNo()) && StringUtils.isNotEmpty(model.getName())) {
213             //e.g. HIP00000009
214             displayedPictureName = model.getCardBaseNo() + "_" + model.getName() + ".jpg";
215         } else {
216             displayedPictureName = null;
217         }
218         return displayedPictureName;
219     }
220 
221     public void setDisplayedPictureName(String displayedPictureName) {
222         this.displayedPictureName = displayedPictureName;
223     }
224 }

jsp代码:

 <tr>  
                    <!-- 图片上传选择框 -->
                    <td class="label"><s:label key="labels.card.base.picture"/></td>
                    <td><s:file name="picture" id="picture" cssStyle="400px"/>
                    
                    <!-- 此处用于显示卡基图片名称和删除按钮 -->
                     <s:if test="picturePath != null && picturePath != '' ">                  
                   <!--   <td class="label"></td> -->                     
                        <!-- 图片名称超链接 -->
                        <s:url id="urlDownloadPicture" action="card-base!download" includeParams="none">
                           <s:param name="pk" value="id"></s:param>
                        </s:url>
                        <s:a href="%{urlDownloadPicture}">${displayedPictureName}</s:a>
                        <!-- 刪除按鈕 -->
                        <s:submit key="labels.card.base.button.deletePicture" name="buttonDeletePicture" id="buttonDeletePicture" onclick="return false;"/>                   
                    </s:if>
                    </td>
                </tr>
                <s:if test="picturePath != null && picturePath != '' ">
                <tr>
                    <td class="label"></td>
                    <td><img src='${pictureWebPath}' height="300px"></td>
                </tr>
                </s:if>

这里面有modelDriven机制,同时在基类定义了相关传递pk后的处理方法。

原文地址:https://www.cnblogs.com/middlesummer/p/3638197.html