標籤:儲存檔案 tco object session fileutils response ext.get void exception
public void UPLOADFILED() {
Date dt = new Date(System.currentTimeMillis());
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String fileName = sdf.format(dt);
int index = getUploadFileName().lastIndexOf(".");
//得到副檔名
String extendName = getUploadFileName().substring(index);
String path = getRootPath()+"up\\";
//String sessionId = getRequest().getSession().getId();
String filename = fileName + extendName;
Json j = uploadFile(filename, path, 200 * 1024 *1024, true);
try {
String json = JSON.toJSONStringWithDateFormat(j,"yyyy-MM-dd");
ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
ServletActionContext.getResponse().getWriter().write(json);
ServletActionContext.getResponse().getWriter().flush();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//writeJson(json);
}
/*public String uploadFile(String path){
return uploadFile(getUploadFileName(), path, 500 * 1024, false);
}*/
/**
* 上傳檔案
* @param filename 檔案名稱
* @param path 檔案儲存路徑
* @param maxSize 上傳檔案的最大大小
* @param overwrite 是否覆蓋已存在的檔案
* @return
*/
public Json uploadFile(String filename, String path, long maxSize, boolean overwrite){
Json j = new Json();
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
String fileName = filename;
String msg = "檔案上傳成功!";
if (! overwrite) {
//檢查並得到新的儲存檔案名稱,防止重名後覆蓋已存在的檔案
fileName = FileUtils.checkFileName(filename, path);
if (FileUtils.isFileExist(fileName, path)) {
/*FileDownloadUtils.downloadJSON("{success:false, msg:‘上傳檔案名稱已存在,請改名後重新上傳!‘}",
getResponse());*/
msg = "上傳檔案名稱已存在,請改名後重新上傳!";
return null;
}
}
if (upload == null) {
/*FileDownloadUtils.downloadJSON("{success:false, msg:‘檔案名稱及路徑名有問題,請修改後重新上傳!‘}",
getResponse());*/
msg = "檔案名稱及路徑名有問題,請修改後重新上傳!";
return null;
}
try {
if (upload.length()> maxSize) {
/*FileDownloadUtils.downloadJSON("{success:false, msg:‘上傳檔案不能大於" + maxSize +",請修改後重新上傳!‘}",
getResponse());*/
msg = "上傳檔案不能大於" + maxSize +",請修改後重新上傳!";
return null;
}
FileUtils.uploadForName(fileName, path, upload);
} catch (IOException e) {
e.printStackTrace();
/*FileDownloadUtils.downloadJSON("{success:false, msg:‘檔案上傳失敗!‘}",
getResponse());*/
msg = "檔案上傳失敗!";
return null;
}
j.setSuccess(true);
j.setMsg(msg);
jsonObject.put("name", fileName);
jsonObject.put("type", FileUtils.converContentType(getUploadContentType()));
jsonObject.put("size", upload.length());
jsonArray.add(jsonObject);
j.setObj(jsonArray);
/*FileDownloadUtils.downloadJSON(
"{success:true, msg:‘檔案上傳成功!‘, " +
"file: {name:‘" + fileName +
"‘, type:‘" + FileUtils.converContentType(getUploadContentType()) +
"‘, size:" + upload.length() + "}}",
getResponse());*/
//errMessage="檔案上傳成功!";
//success = true;
return j;
}
easyUI + swfupload 多附件上傳功能