java struts2上传文件(ajaxfileupload.js)

html部分代码:

<input type='file' size='20' style='height: 25px;width:60%;' name='file' id='corp_icon_id'>
<input type='button' onclick="uploadFile('corp_icon_id')" value='上传'>

 

js部分代码:

function uploadFile(fileId) {
var fileIdValue = $("#" + fileId).val();
if (!fileIdValue) {
mini.alert('请选择要上传的文件!', '提示');
} else {
doSaveByfreshFlag(false);
jQuery.ajaxFileUpload({
url : '<%=basePath%>basicData/OperationUnits_uploadFile.action',
secureuri : false,
fileElementId : fileId,
dataType : 'text',
type : "POST",
data : {
"fileFullName":fileIdValue,
"tcorp.corp_id":corp_id
},
success : function(data, status) {
window.location.href ="basicData/OperationUnits_edit.action?primaryKey=" + corp_id +"&optype=edit";
},
error : function(data, status, e) {
mini.alert('上传失败!', '提示');
}
});
return false;
}
 
}

 

java部分代码:

private File file;//实现get和set方法
 
 
public String uploadFile() {
String fileFullName = this.getParameter("fileFullName");
String id = this.getParameter("id");
String corpId = this.getParameter("corp_id");
String suffixName = fileFullName.substring(fileFullName.lastIndexOf("."));
String showName = fileFullName.substring(fileFullName.lastIndexOf("\\") + 1);
 
String uploadRelativePath = "upload/images/";
String Serverpath = this.getServletContext().getRealPath("/");
String uploadFullPath = Serverpath + uploadRelativePath;
File tempFile = this.getFile();
File outFile = new File(uploadFullPath); // 判断文件夹是否存在,如果不存在则创建文件夹
if (!outFile.exists()) {
outFile.mkdirs();
}
UUIDHexGenerator t = new UUIDHexGenerator(); // 文件名不能重复
String saveRelativeFileName = uploadRelativePath + t.generate() + suffixName;
String saveFullFileName = Serverpath + saveRelativeFileName;
try {
FileInputStream inputStream = new FileInputStream(tempFile);
FileOutputStream outputStream = new FileOutputStream(saveFullFileName);
byte[] buf = new byte[1024];
int length = 0;
while ((length = inputStream.read(buf)) != -1) {
outputStream.write(buf, 0, length);
}
inputStream.close();
outputStream.flush();
outputStream.close();
 
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
 
this.tcorp.setCorp_icon(saveRelativeFileName);
int resultCount = 0;
resultCount = this.basicDataService.updateTcorp(tcorp);
 
HashMap<String, String> resultMap = new HashMap<String, String>();
resultMap.put("count", resultCount + "");
String result = PluSoft.Utils.JSON.Encode(resultMap);
this.ajax(result);
return null;
}

 

 

 

你可能感兴趣的:(ajaxFileUpload)