導入 AjaxFileUpload.js 文件
js代碼
$.ajaxFileUpload({
url: 'upload',//處理圖片腳本
secureuri : false,
fileElementId : 'uploadImg',//file控件id
data: {photoType: photoType},//參數
dataType : 'json', //參數大寫 否則谷歌瀏覽器可能報錯
success : function (data,status){
data=jQuery.parseJSON(data);
$("#hideImgPath").val(data.filePath);
alert("上傳圖片成功!");
},
error: function(data, status, e){
alert("上傳圖片失敗!請稍後重試!");
}
});
html代碼
<span class="d">
<input type="file" id="uploadImg" name="uploadImg" value="" />
<input type="button" id="uploadImgButton" onclick="uploadSaveImg();" value="確定上傳" />
<input type="hidden" value="" id="hideImgPath" name="hideImgPath"/>
</br>格式一般爲GIF或者JPEG,大小100*100像素;
</span>
java 代碼
/**
* 方法描述: 上傳屬性值圖片
* @author Andy 2014-8-14 下午02:09:50
*/
@RequestMapping("attribute/upload")
public void upload(HttpServletRequest request,HttpServletResponse response){
Map<String, Object> resultMap=new HashMap<String, Object>();
String imgName=getFileName();
String saveImgPath=request.getSession().getServletContext().getRealPath("/upload/image"); //項目圖片保存路徑
File fileIMG=new File(saveImgPath);//圖片保存路徑
if (!fileIMG.exists()) {
fileIMG.mkdirs();
}
try {
String filePath="";
MultipartHttpServletRequest mhs = (MultipartHttpServletRequest) request;
MultipartFile file = mhs.getFile("uploadImg");
String photoType=mhs.getParameter("photoType");
imgName = imgName+"."+photoType;
if(file!=null){
filePath = SaveFileFromInputStream(file.getInputStream(),saveImgPath,imgName);
}
resultMap.put("filePath","upload/image/"+imgName);
resultMap.put("imgName",imgName);
} catch (Exception e) {
logger.error(e.getMessage());
System.out.println("上傳圖片失敗,請重試!");
}
resultMap.put("status", "true");
displayToJson(resultMap, response);
}
/**
* 方法描述: 保存圖片
* @param stream
* @param path
* @param filename
* @return
* @throws IOException String
* @author Andy 2014-8-14 下午02:59:10
*/
public String SaveFileFromInputStream(InputStream stream,String path,String filename) throws IOException{
String filePath = path + File.separator+ filename;
FileOutputStream fs=new FileOutputStream(filePath);
byte[] buffer =new byte[1024*1024];
int bytesum = 0;
int byteread = 0;
while ((byteread=stream.read(buffer))!=-1){
bytesum+=byteread;
fs.write(buffer,0,byteread);
fs.flush();
}
fs.close();
stream.close();
return filePath;
}
/**
* 方法描述: 獲取文件的名稱
* @return String
* @author Andy 2014-8-15 上午09:51:58
*/
public static String getFileName(){
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String str=sdf.format(new Date()).replace(" ", "-").split(":")[0];
String sop=Long.toString(System.currentTimeMillis());
sop=sop.substring(5, sop.length());
return str+"-"+sop; //2014-08-15-10-68194635 日期-小時
}
解決辦法:在springMVC配置文件中 添加如下配置信息:
<!-- 避免IE執行AJAX時,返回JSON出現下載文件 -->
<bean id="mappingJacksonHttpMessageConverter"
class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
同時設置返回數據的類型: response.setContentType("text/plain;charset=UTF-8");
所遇問題2:返回的數據中帶有<pre> 標籤
解決辦法: 將AjaxFileUpload.js文件中 eval( "data = " + data ); 改成 data = jQuery.parseJSON(jQuery(data).text());
此時如果在頁面上還是無法解析時,請再將 返回數據轉成Json 一遍 data=jQuery.parseJSON(data);
所遇問題3: 在使用springMVC時 後臺接收不到 前臺的 File 時 報錯:
nested exception is java.lang.NoClassDefFoundError:org/apache/commons/io/output/DeferredFileOutputStreamat
org.springframework.web.servlet.DispatcherServlet.triggerAfterCompletionWithError(DispatcherServlet.java:1259)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:945)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:915)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:822)
java.lang.ClassNotFoundException:
org.apache.commons.io.output.DeferredFileOutputStream
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1358)
at org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1204)
at org.apache.commons.fileupload.disk.DiskFileItemFactory.createItem(DiskFileItemFactory.java:199)
解決辦法: 1、 添加 commons-io-1.3.1.jar 包 ,此包是上傳所依賴的包 。
2、如果添加此包後還是提示找不到本包 原因可能有兩點:①、tomcat 沒有加載本包,此時請到tomcat下 將此包勾選上 。 ②如果出現本包衝突時 將tomcat下
的同名jar包 刪掉