ajax jQuery 实现文件上传
1.上传jsp。
<table cellpadding="0" cellspacing="0" border="0" >
<tr>
<td><input type="file" name="upoadFileName" id="upoadFileName"><a href="#" onclick="uploadFile();return false;"><span><span>上传</span></span></a></td>
</tr>
<tr>
<td> </td>
</tr>
</table>
2.下面是前端的js脚本:
function uploadFile(){
var myurl="/uploadMyFile.do?tenderInfoId="+tenderInfoId;
jQuery.ajaxFileUpload(
{
url:myurl,
secureuri:false,
fileElementId:""upoadFileName"", --上传文件对应的文本域的id
dataType: ""json"",
success: function (data, status)
{
alert(""上传成功"");
},
error: function (data, status, e)
{
alert(""上传失败"");
}
} );
}
3.这是后台的action:
public ActionForward uploadMyFile(ActionMapping mapping,
ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws Exception {
/* =============禁止缓存============== */
response.setHeader("Pragma", "no-cache");
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Expires", "0");
/* =============禁止缓存============== */
response.setContentType("text/html;charset=UTF-8");
TTenderFileDTO tendform = (TTenderFileDTO) form;
MultipartHttpServletRequest mhs = (MultipartHttpServletRequest) request;
MultipartFile mf = mhs.getFile("batchSearchFile");
String filewholeName = "";
try {
FormFile file = (FormFile) tendform.getMultipartRequestHandler()
.getFileElements().get("upoadFileName");--对应于前端的文本域id,
String fileName = file.getFileName();
String fileSimpleName = fileName.substring(fileName
.lastIndexOf("."));
fileName = DateHandler.convertStringToDate(new Date(), null)
+ fileName;
if (file.getFileSize() > 50 * 1024 * 1024) {
write("{""result"":false,""error"":"" filesize""}", response);
return null;
}
String uploadPath = this.getServlet().getServletContext()
.getRealPath("/")
+ "uploadfile/";
File savePath = new File(uploadPath);
System.out.println(savePath.getAbsolutePath());
if (!savePath.exists()) {
savePath.mkdir();
}
filewholeName = uploadPath + "/" + fileName;
FileOutputStream fos = new FileOutputStream(filewholeName);
fos.write(file.getFileData());
log.info("#############上传文件:" + fileName);
write("{""result"":true}", response);
} catch (Exception e) {
write("{""result"":false,""error"":""" + e.getMessage() + """}", response);
}
return null;
}