前端用了jquery.form.js插件異步提交表單
$("#imgForm").ajaxSubmit();//戶主頭像
/**
*
* @description 上傳戶主頭像
* @author 邵海雄
* @date 2016年8月12日 上午9:39:26
*/
public void holdHead(){
//上傳文件名(以當前系統時間為准)
String uploadfileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date(System.currentTimeMillis()));
UploadFile uploadFile = getFile("photoFilePic");//獲得上傳文件
File source = uploadFile.getFile(); //源文件
String fileName = uploadFile.getFileName(); //獲得源文件文件名
String extension = fileName.substring(fileName.lastIndexOf(".")); //得到源文件的后綴
String uploadPath = PathKit.getWebRootPath()+"/upload/household"; //上傳文件的路徑
//服務器上的圖片地址,添加到數據庫的圖片地址
String imgSrc="/upload/household/"+uploadfileName+extension;
ViewModel viewModel = AntipovertyCommonService.upload(uploadPath,source, uploadfileName+extension);
String householdId = getPara("householdId_img");
if (StrKit.notBlank(householdId)) {
//拿到戶主ID更新圖片地址
boolean flag= PovertyService.updateHouseholdHeadById(householdId,imgSrc);
}
renderJson();
}
/**
*
* @description 文件上傳
* @author 邵海雄
* @return
* @date 2016年8月9日 下午 15:54:39
*/
public static ViewModel upload(String uploadPath,File source,String uploadFileName) {
ViewModel vm = new ViewModel();
try {
FileInputStream fis = new FileInputStream(source); //源文件輸入
File targetDir = new File(uploadPath);//上傳文件parent
if (!targetDir.exists()) {
targetDir.mkdirs(); //如果目標路徑不存在新建一個
}
File target = new File(targetDir,uploadFileName);//上傳文件
if(!target.exists())
{
target.createNewFile();
}
FileOutputStream fos = new FileOutputStream(target);//上傳文件輸出
byte[] bts = new byte[300];
while (fis.read(bts, 0, 300) != -1) { // 讀取到數組
fos.write(bts, 0, 300); //寫入
}
fis.close();
fos.close();
source.delete();
vm.setInfo(new Info("上傳成功"));
} catch (FileNotFoundException e) {
vm.setErr(new Error("上傳出現錯誤,請稍后再上傳"));
} catch (IOException e) {
} vm.setErr(new Error("文件寫入服務器出現錯誤,請稍后再上傳"));
return vm;
}