html5圖片上傳【文件上傳】
在網上找了很多資料,主要也就2種
1.from表單提交的方式
<form action="pushUserIcon" method="post" enctype="multipart/form-data">
<table>
<tr>
<td width="50" align=left>圖片:</td>
<td><input type="file" name="file"/></td>
</tr>
<tr>
<td width="50" align="left">用戶id:</td>
<td><input type="text" name="userId"/></td>
</tr>
<tr>
<td><input type="submit"> </td>
</tr>
</table>
</form>
注意: enctype="multipart/form-data" 必須要填
1.1.Java頁面直接提交:
@RequestMapping(value="/pushUserIcon",method=RequestMethod.POST)
@ResponseBody
public String pushUserIcon(HttpServletRequest request, HttpServletResponse response) throws IOException,BaseException {
String result = null;
String userId = request.getParameter("userId");
try{
//轉型為MultipartHttpRequest(重點的所在)
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//獲得第1張圖片(根據前台的name名稱得到上傳的文件)
MultipartFile file = multipartRequest.getFile("file");
result = uploadImageServic.uploadFile(file, request, userId);
System.out.println("result:" + result);
response.setContentType("text/html;charset=utf8");
response.getWriter().write("result:" + result);
}catch(Exception e){
BaseException baseException = new BaseException(e);
baseException.setErrorMsg("Upload API Exception");
throw baseException;
}
return null;
}
1.2.原生js 和jQuery的網上有很多,這里就不多說了。
1.2.1. fromData創建的兩種方式
var formData = new FormData($("#myForm")[0]);//用form 表單直接 構造formData 對象; 就不需要下面的append 方法來為表單進行賦值了。
//var formData = new FormData();//構造空對象,下面用append 方法賦值。
// formData.append("policy", "");
// formData.append("signature", "");
// formData.append("file", $("#file_upload")[0].files[0]);
2.不用from表單提交:
<table style="border: 1px solid black; width: 100%">
<tr>
<td width="50" align=left>圖片:</td>
<td><input type="file" id="imageFile" name="img" multiple="multiple"/></td>
<td>
<input type="button" value="調用" onclick="pushImg()" />
</td>
</tr>
</table>
HTML就這些,我想大家應該都能看懂,下面就要說說這2種提交方式,Ajax是如何編碼?【from表單提交方式也可以使用js或者直接提交頁面刷新】
Ajax編碼也有2種:
1.原生js
function sub()
{
var file = document.getElementById("imageFile");
var files = file.files;
for(var i = 0 ; i < files.length;i++)
{
uploadFile(files[i]);
}
}
var xhr = null;
function uploadFile(file) {
xhr = new XMLHttpRequest();
/* xhr.addEventListener("error", uploadFailed, false);
xhr.addEventListener("abort", uploadCanceled, false); */
xhr.open("post", "upload/", true); //訪問控制器是upload,后面必須加'/'否則會報錯"org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.Mult...",但是如果是多級的URL【例如XX/XXX/00/upload/0】又沒問題了.
var fd = new FormData();
fd.append("userID", "1");
fd.append("errDeviceType", "001");
fd.append("errDeviceID", "11761b4a-57bf-11e5-aee9-005056ad65af");
fd.append("errType", "001");
fd.append("errContent", "XXXXXX");
fd.append("errPic", file);
xhr.send(fd);
xhr.onreadystatechange = cb;
}
function cb()
{
if(xhr.status == 200)
{
var b = xhr.responseText;
if(b == "success"){
alert("上傳成功!");
}else{
alert("上傳失敗!");
}
}
}
2.jquery
function pushImg(obj) {
debugger;
var url = "upload/"; //訪問控制器是upload,后面必須加'/'否則會報錯"org.apache.catalina.connector.RequestFacade cannot be cast to org.springframework.web.multipart.Mult...",但是如果是多級的URL【例如XX/XXX/00/upload/0】又沒問題了.
var param = $("#errorParameter").val();
var files = $("#imageFile").get(0).files[0]; //獲取file控件中的內容
var fd = new FormData();
fd.append("userID", "1");
fd.append("errDeviceType", "001");
fd.append("errDeviceID", "11761b4a-57bf-11e5-aee9-005056ad65af");
fd.append("errType", "001");
fd.append("errContent", "XXXXXX");
fd.append("errPic", files);
$.ajax({
type: "POST",
contentType:false, //必須false才會避開jQuery對 formdata 的默認處理 , XMLHttpRequest會對 formdata 進行正確的處理
processData: false, //必須false才會自動加上正確的Content-Type
url: url,
data: fd,
success: function (msg) {
debugger;
var jsonString = JSON.stringify(msg);
$("#txtTd").text(jsonString)
alert(jsonString);
},
error: function (msg) {
debugger;
alert("error");
}
});
}
現在前端的就應該差不多了,現在就是接口了,我的參數和訪問路徑都好了,現在就差接口服務了:
spring mvc框架:
@RequestMapping(value = { "upload" })
public void pushErrorData(HttpServletRequest request,
HttpServletResponse response) throws BaseException {
String userID=request.getParameter("userID");
// 轉型為MultipartHttpRequest(重點的所在)這個就是上面ajax中提到如果直接訪問此接口而不加"/",此轉型就會報錯
MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
//MultipartFile file = multipartRequest.getFiles("errPic");//獲取文件集合 對應 jquery $("#imageFile").get(0).files
// 獲得第1張圖片(根據前台的name名稱得到上傳的文件)
MultipartFile file = multipartRequest.getFile("errPic"); //對應 jquery $("#imageFile").get(0).files[index]
Map<String, Object> map = new HashMap<String, Object>();
if (null!=file && !file.isEmpty()) {
try {
map = Common.uploadFile(file);
} catch (IOException e) {
BaseException baseException = new BaseException(e);
//baseException.setErrorMsg(imgErrorMsg);
throw baseException;
}
}
}
/**
* 圖片上傳
*
* @param file
* @return
* @throws IOException
* @throws BaseException
*/
public static Map<String, Object> uploadFile(MultipartFile file)
throws IOException, BaseException {
String fail = ConfigBundleHelper.getValue("busConfig", "fail");//上傳失敗狀態
String success = ConfigBundleHelper.getValue("busConfig", "success");//上傳成功狀態
String errorMsg = ConfigBundleHelper.getValue("busConfig","imgErrorMsg");//上傳錯誤信息
String filePath = ConfigBundleHelper.getValue("busConfig", "filePath");//上傳路徑,本來是相對路徑,但是在發布后路徑會創建在tomcat的bin目錄下,所以接口上傳的路徑是一個難題,我用的是絕對路徑,等到發布到Linux環境中,通過配置文件修改路徑為Linux中的資源地址【防止工程刪除而資源文件不會丟失】,然后重新發布工程時再通過Linux的命令把我們需要的資源文件導入到我們發布的工程項目中。
String size = ConfigBundleHelper.getValue("busConfig", "fileSize");
String interfaceService = ConfigBundleHelper.getValue("busConfig",
"interfaceService");
long maxFileSize = (Integer.valueOf(size)) * 1024 * 1024;
String suffix = file.getOriginalFilename().substring(
file.getOriginalFilename().lastIndexOf("."));
long fileSize = file.getSize();
Map<String, Object> map = new HashMap<String, Object>();
if (suffix.equals(".png") || suffix.equals(".jpg")) {
if (fileSize < maxFileSize) {
// System.out.println("fileSize"+fileSize);
String fileName = file.getOriginalFilename();
fileName = new String(fileName.getBytes("ISO-8859-1"), "UTF-8");
File tempFile = new File(filePath, new Date().getTime()
+ fileName);
try {
if (!tempFile.getParentFile().exists()) {
tempFile.getParentFile().mkdirs();//如果是多級文件使用mkdirs();如果就一層級的話,可以使用mkdir()
}
if (!tempFile.exists()) {
tempFile.createNewFile();
}
file.transferTo(tempFile);
} catch (IllegalStateException e) {
BaseException baseException = new BaseException(e);
baseException.setErrorMsg(errorMsg);
throw baseException;
}
map.put("SUCESS", success);
map.put("data",interfaceService + filePath + new Date().getTime() + tempFile.getName());
} else {
map.put("SUCESS", fail);
map.put("data", "Image too big");
}
} else {
map.put("SUCESS", fail);
map.put("data", "Image format error");
}
return map;
}
這是我在工作中所遇到到問題,分享給大家,希望大家不會在這個問題上花費大量的時間。謝謝
