JAVA檔案上傳工具類__JAVA

來源:互聯網
上載者:User
package com.ccxe.trust.proselect.action;import java.io.File;import java.io.FileInputStream;import java.io.InputStream;import java.io.PrintWriter;import java.io.UnsupportedEncodingException;import java.net.URLEncoder;import java.util.List;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import org.apache.log4j.Logger;import org.apache.struts2.ServletActionContext;import org.springframework.web.context.ContextLoader;import org.springframework.web.context.WebApplicationContext;import com.ccxe.common.util.FileUtil;import com.ccxe.common.util.StringUtil;import com.ccxe.common.web.BaseAction;import com.ccxe.trust.proselect.pojo.BAtta;import com.ccxe.trust.proselect.service.IProSelectCommonService;import com.ccxe.trust.proselect.util.ProConstants;import com.ccxe.trust.proselect.util.TrustConfig;/** * 附件上傳Action *  *  * Dec 3, 2013 */public class AttachmentUploadAction extends BaseAction {private static final long serialVersionUID = 1L;private Logger log = Logger.getLogger(AttachmentUploadAction.class);private IProSelectCommonService proSelectCommonService;private File[] upload;// 實際上傳檔案private String[] uploadContentType; // 檔案的內容類型private String[] uploadFileName; // 上傳檔案名稱private List<String> attType;private BAtta attachment;//錯誤資訊private String msg = "";/** * 響應操作:上傳各項附件 */public String upload() {try {JSONArray array = new JSONArray();JSONObject json = null;if(null != upload) {for(int i = 0;i<upload.length;i++) {if(this.upload[i].length() < ProConstants.FILE_SIZE) {if(this.proSelectCommonService.checkAttachment(attachment.getRelaId(), attachment.getAttCata(), attType.get(i)) == 0){BAtta att = null;String ioFileName = FileUtil.writerFile(upload[i],uploadFileName[i]);if(StringUtil.isNotNull(ioFileName)) {att = new BAtta();att.setRelaId(attachment.getRelaId());att.setAttTitle(uploadFileName[i]);att.setAttSrcTitle(uploadFileName[i]);att.setAttCata(attachment.getAttCata());att.setAttPath(ioFileName);att.setAttType(attType.get(i));att.setStatus(ProConstants.DC_BL_STATUS.BOOL_YES);att.setCreateUser(this.getSessionUserInfo().getUserID());att.setUpdateUser(this.getSessionUserInfo().getUserID());att.setAttSeqNum(i+1);this.getProSelectCommonService().saveProAttachment(att);}}else {  //此類別附件已存在json = new JSONObject();json.put("msg","【" + attType.get(i) + "】附件已存在,可以刪除以後再上傳.");array.add(json);}}else {   //上傳檔案大於限制大小json = new JSONObject();json.put("msg", "【" + attType.get(i) + "】上傳檔案超過系統限制" + ProConstants.FILE_SIZE / (1024*1024) + "M.");array.add(json);}}}msg = array.size() > 0 ? java.net.URLEncoder.encode(array.toString(),"UTF-8"): "";} catch (Exception e){e.printStackTrace();return INPUT;}return SUCCESS;}/** * 響應操作:刪除附件 * @return */public String removeAttachment() {PrintWriter out = null;JSONObject json = new JSONObject();try {HttpServletResponse response = ServletActionContext.getResponse();response.setContentType("text/html;charset=UTF-8");out = response.getWriter();String attId = (String)this.getAppRequestParameterByName("attId");if(StringUtil.isNotNull(attId)) {this.proSelectCommonService.deleteProAttachment(attId);}json.put("status","success");json.put("id", attId);out.print(json.toString());}catch(Exception e) {log.error("刪除附件出錯",e);json.put("status","error");out.print(json.toString());}finally {if (out != null) {out.flush();out.close();}}return null;}private String fileName;// 初始的通過param指定的檔案名稱屬性        private String inputPath;// 指定要被下載的檔案路徑/** * 響應操作:下載附件 * @return */    public String download() {    try{    WebApplicationContext wac = ContextLoader.getCurrentWebApplicationContext();TrustConfig  trustConfig =  (TrustConfig)wac.getBean(ProConstants.configBeanName);//模組設定檔String attId = (String)this.getAppRequestParameterByName("attId");if(StringUtil.isNotNull(attId)) {this.attachment = this.getProSelectCommonService().fetchAttachment(attId);if(null != attachment) {//inputPath =  trustConfig.getTrustProselectCustFilePath()+"/" +attachment.getAttPath();inputPath =  trustConfig.getTrustProselectCustFilePath()+ attachment.getAttPath();//20140528 zhaocg modified:設定檔中統一加了///fileName = java.net.URLEncoder.encode(attachment.getAttSrcTitle(),"UTF-8");fileName = attachment.getAttSrcTitle();}}    File file = new File(inputPath);    if(!file.exists()) {    this.getAppRequest().setAttribute("errorMsg","下載的附件不存在或已被刪除。");    return ERROR;    }    }catch(Exception e){    log.error("下載附件出錯",e);    return ERROR;    }    return SUCCESS;    }    public String getDownloadFileName() {String downFileName = fileName;try {HttpServletRequest request = getAppRequest();String agent = request.getHeader("USER-AGENT");if(null != agent && -1 != agent.indexOf("theworld")){//世界之窗downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1");    //解決下載的檔案名稱中含有小括弧轉變義符%28%29}else if(null != agent && -1 != agent.indexOf("MSIE 8.0")){//IE8//downFileName = java.net.URLDecoder.decode(downFileName,"UTF-8");downFileName =URLEncoder.encode(downFileName, "UTF-8").replace("+","%20"); }else if(null != agent && -1 != agent.indexOf("MSIE 7.0") && -1 != agent.indexOf("SE 2.X MetaSr 1.0")){//sogo瀏覽器downFileName =URLEncoder.encode(downFileName, "UTF-8").replace("+","%20"); }else if(null != agent && (-1 != agent.indexOf("SV1") || -1 != agent.indexOf("360SE"))){//360安全瀏覽器downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1"); }else if(null != agent && -1 != agent.indexOf("Chrome")){//google//fileName = URLEncoder.encode(downFileNameCN,"UTF-8").replace("+","%20");downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1"); //解決下載的檔案名稱中含有小括弧轉變義符%28%29}else if(null != agent && -1 != agent.indexOf("Firefox")){//Firefox//downFileName = java.net.URLDecoder.decode(downFileName,"UTF-8");downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1");}else if(null != agent && -1 != agent.indexOf("Safari")){//Safari downFileName = new String(downFileName.getBytes("UTF-8"), "ISO8859-1");}else if(null != agent && -1 != agent.indexOf("Opera")){//OperadownFileName = new String(downFileName.getBytes("UTF-8"), "ISO8859-1");}else {//其它瀏覽器downFileName = new String(downFileName.getBytes("gb2312"), "ISO8859-1");}}catch(UnsupportedEncodingException e) {               e.printStackTrace();    }    return downFileName;    }public InputStream getInputStream() throws Exception {    InputStream inputStream = new FileInputStream(new File(inputPath));    return inputStream;    }public File[] getUpload() {return upload;}public void setUpload(File[] upload) {this.upload = upload;}public String[] getUploadContentType() {return uploadContentType;}public void setUploadContentType(String[] uploadContentType) {this.uploadContentType = uploadContentType;}public String[] getUploadFileName() {return uploadFileName;}public void setUploadFileName(String[] uploadFileName) {this.uploadFileName = uploadFileName;}public List<String> getAttType() {return attType;}public void setAttType(List<String> attType) {this.attType = attType;}public BAtta getAttachment() {return attachment;}public void setAttachment(BAtta attachment) {this.attachment = attachment;}public IProSelectCommonService getProSelectCommonService() {return proSelectCommonService;}public void setProSelectCommonService(IProSelectCommonService proSelectCommonService) {this.proSelectCommonService = proSelectCommonService;}public String getMsg() {return msg;}public void setMsg(String msg) {this.msg = msg;}}
<!-- 附件 --><action name="att_*" class="com.ccxe.trust.proselect.action.AttachmentUploadAction" method="{1}"><result type="redirect">/proSelect/proSetup_fetchProAtt.action?proId=${attachment.relaId}&msg=${msg}</result></action><!-- 附件下載 --><action name="downloadAtt" class="com.ccxe.trust.proselect.action.AttachmentUploadAction" method="download">              <param name="inputPath">${inputPath}</param>              <!-- 初始檔案名稱 -->              <param name="fileName">${fileName}</param>              <result name="success" type="stream">                  <param name="contentType">application/octet-stream;charset=UTF-8</param>                  <param name="inputName">inputStream</param>                  <!-- 使用經過轉碼的檔案名稱作為下載檔案名稱,downloadFileName屬性對應action類中的方法 getDownloadFileName() -->                  <param name="contentDisposition">attachment;filename="${downloadFileName}"</param>                  <param name="bufferSize">4096</param>              </result>        </action>


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.