方法一:使用ajax異步提交
此種方法的好處是可以回調響應結果。
html代碼:
<form action="${basePath}/save" method="post" name="form" id="form">
<table>
<tr>
<td>名稱:</td>
<td><input type="text" id="title" name="entity.title" class="input"></td>
</tr>
<tr>
<td>圖片:</td>
<td>
<input type="file" id="uploadImage" name="uploadImage"
accept="image/gif,image/png,image/jpeg,image/bmp"/>
<input type="hidden" id="imgUrl" name="entity.imgUrl"
value="<s:property value='entity.imgUrl'/>">
<span>提示:文件大小不超過200k,建議圖片寬高爲300px*300px</span>
</td>
</tr>
<tr>
<td>
<input type="button" onclick="doSubmit()" value="提交"/>
<input type="reset" value="取消">
</td>
</tr>
</table>
</form>
使用的是ajax異步單獨處理並提交,此處form表單的enctype="multipart/form-data"屬性可以不添加。
js處理代碼:
function doSummit(){
var formData=new FormData($("#formId")[0]);
$.ajax({
url:url,
type: 'post',
cache: false, //上傳文件不需要緩存
async : true,
data: formdata,
processData: false, // 此處是關鍵:告訴jQuery不要去處理髮送的數據
contentType: false, // 此處是關鍵:告訴jQuery不要去設置Content-Type請求頭
success: function (data) {
//處理成功後動作,比如調轉window.location.href ='/list'
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
此處contentType和processDate屬性必須添加,否則後臺無法接收。
方法二:使用form表單自帶的submit功能直接提交
html代碼:
<form action="${basePath}/save" method="post" name="form" id="form enctype="multipart/form-data">
<table>
<tr>
<td>名稱:</td>
<td><input type="text" id="title" name="entity.title" class="input"></td>
</tr>
<tr>
<td>圖片:</td>
<td>
<input type="file" id="uploadImage" name="uploadImage"
accept="image/gif,image/png,image/jpeg,image/bmp"/>
<input type="hidden" id="imgUrl" name="entity.imgUrl"
value="<s:property value='entity.imgUrl'/>">
<span>提示:文件大小不超過200k,建議圖片寬高爲300px*300px</span>
</td>
</tr>
<tr>
<td>
<input type="submit" value="提交"/>
<input type="reset" value="取消">
</td>
</tr>
</table>
</form>
點擊提交按鈕,觸發form表單的提交操作,直接將數據提交到後臺,此處必須配置enctype="multipart/form-data"。
java統一處理代碼:
@RequestMapping("/save")
@ResponseBody
public JSONObject Edit(HttpSession session, HttpServletRequest request,
@RequestParam(value = "file", required = false) MultipartFile file,
Entity entity) {
JSONObject json = new JSONObject();
try {
// 獲取圖片原始文件名
String originalFilename = file.getOriginalFilename();
// 文件名使用當前時間
String name = new SimpleDateFormat("yyyyMMddHHmmssSSS").format(new Date());
// 獲取上傳圖片的擴展名(jpg/png/...)
String extension = originalFilename.subString(originalFilename.lastIndexOf(".")).toLowerCase();
// 圖片上傳的相對路徑(因爲相對路徑放到頁面上就可以顯示圖片)
String path = "/upload/" + name + "." + extension;
// 圖片上傳的絕對路徑
String url = request.getSession().getServletContext().getRealPath("") + path;
File dir = new File(url);
if (!dir.exists()) {
dir.mkdirs();
}
// 上傳圖片
file.transferTo(new File(url));
// 將相對路徑寫回(json格式)
JSONObject jsonObject = new JSONObject();
// 將圖片上傳到本地
jsonObject.put("path", path);
// 設置響應數據的類型json
response.setContentType("application/json; charset=utf-8");
// 寫回
response.getWriter().write(jsonObject.toString());
} catch (Exception e) {
throw new RuntimeException("服務器繁忙,上傳圖片失敗");
}
}