個人JSP:
javascript
<script language="javascript" src="js/event/ajaxfileupload.js"></script>css
<script type="text/javascript">html
function ajaxFileUpload(){java
//開始上傳文件時顯示一個圖片,文件上傳完成將圖片隱藏ajax
//$("#loading").ajaxStart(function(){$(this).show();}).ajaxComplete(function(){$(this).hide();});json
//執行上傳文件操做的函數安全
$.ajaxFileUpload({服務器
//處理文件上傳操做的服務器端地址(能夠傳參數,已親測可用)app
url:'${pageContext.request.contextPath}/uploadSave.do',ide
secureuri:false, //是否啓用安全提交,默認爲false
fileElementId:'imgFile', //文件選擇框的id屬性
dataType:'text', //服務器返回的格式,能夠是json或xml等
success:function(data, status){ //服務器響應成功時的處理函數
data = data.replace(/<pre.*?>/g, ''); //ajaxFileUpload會對服務器響應回來的text內容加上<pre style="....">text</pre>先後綴
data = data.replace(/<PRE.*?>/g, '');
data = data.replace("<PRE>", '');
data = data.replace("</PRE>", '');
data = data.replace("<pre>", '');
data = data.replace("</pre>", ''); //本例中設定上傳文件完畢後,服務端會返回給前臺[0`filepath]
if(data.substring(0, 1) == 0){ //0表示上傳成功(後跟上傳後的文件路徑),1表示失敗(後跟失敗描述)
$("img[id='uploadImage']").attr("src", data.substring(2));
$("img[id='uploadImage']").css("display", "");
$('#result').html("圖片上傳成功<br/>");
}else if(data.substring(0, 1) == 1){
$('#result').html('圖片格式只能是jpg、jpeg、bmp、gif,請重試!!');
}else{
$('#result').html('圖片上傳失敗,請重試!!');
}
},
error:function(data, status, e){ //服務器響應失敗時的處理函數
$('#result').html('圖片上傳失敗,請重試!!');
}
});
// $(document).getElementById("uploadForm").submit();
}
</script>
<img id="uploadImage" src="" style="display: none;width: 175px;height: 260px;"/>
<input name="myfiles" id="imgFile" type="file" value=""/> <br> <br>
<input type="button" value="上傳" style="width:50px;height: 25px;"/>
@RequestMapping(value="uploadSave.do")
public String saveUpload(HttpServletRequest request,@RequestParam MultipartFile[] myfiles,HttpServletResponse response) throws IOException {
String path = "";
MultipartFile imgFileName = myfiles[0];
//
List fileTypes = new ArrayList();
fileTypes.add("jpg");
fileTypes.add("jpeg");
fileTypes.add("bmp");
fileTypes.add("gif");
String booleanString = "";
if(imgFileName.getOriginalFilename()!=null||!"".equals(imgFileName.getOriginalFilename())){
booleanString = this.getFile(imgFileName, fileTypes,request);
}
//設置響應給前臺內容的PrintWriter對象
PrintWriter out = response.getWriter();
String outPrint = "0`" + "/upload/" + imgFileName.getOriginalFilename();
if("1".equals(booleanString)){
outPrint = "1`" + "/upload/" + imgFileName.getOriginalFilename();
}
out.print(outPrint);
out.flush();
return null;
}
private String getFile(MultipartFile imgFileName,List fileTypes,HttpServletRequest request)throws IOException {
String fileName = imgFileName.getOriginalFilename();
//獲取上傳文件類型的擴展名,先獲得.的位置,再截取從.的下一個位置到文件的最後,最後獲得擴展名
String ext = fileName.substring(fileName.lastIndexOf(".")+1,fileName.length());
//對擴展名進行小寫轉換
ext = ext.toLowerCase();
String uploadFileName = "";
if(fileTypes.contains(ext)) { //若是擴展名屬於容許上傳的類型,則建立文件
// file = this.creatFolder(imgFileName,fileName);
String uploadPath = "/upload";
String realUploadFilePath = request.getSession().getServletContext().getRealPath(uploadPath);
String realUploadFileName = realUploadFilePath + File.separator + fileName;
uploadFileName = uploadPath + "/" + fileName;
// if(!StringUtils.isEmpty(dir)){
// realUploadFilePath = realUploadFilePath + File.separator + dir;
// uploadFilePath = uploadFilePath + "/" + dir;
// }
InputStream in = imgFileName.getInputStream();
moveFileToPath(in,realUploadFileName);
// try {
// imgFileName.transferTo(file); //保存上傳的文件
// } catch (IllegalStateException e) {
// e.printStackTrace();
// } catch (IOException e) {
// e.printStackTrace();
// }
} else{
uploadFileName = "1";
}
return uploadFileName;
}
public static void moveFileToPath(InputStream is,String path) throws IOException{
File newfile = new File(path);
// 新文件目錄不存在,則建立
newfile = newfile.getParentFile();
if (!newfile.exists()){
newfile.mkdirs();
}
FileOutputStream fos = new FileOutputStream(path);
int count = 0;
byte[] buffer = new byte[8192];
while ((count = is.read(buffer)) != -1){
fos.write(buffer, 0, count);
}
fos.close();
is.close();
}