標籤:jsp+springmvc圖片上傳立刻回 ssh spring 非同步
思路:onchange()事件觸發非同步請求,js將成功後返回圖片的地址動態寫入
JSP頁面: 外層一個ID為myForm的表單
<pre name="code" class="html"> <a name="uploadImgs" id="uploadImgs"></a> <p><label><samp>*</samp>上傳產品圖片(XX尺寸):</label><span id="uploadImgTip1" class="orange">注:該尺寸圖片必須為90x150。</span></p> <p><label></label><img id='imgSize1ImgSrc' src='${path}/ecps/console/images/logo266x64.png' height="100" width="100" /><input type='file' id='imgSize1File' name='imgSize1File' class="file" onchange='submitImgSize1Upload()' /><span class="pos" id="imgSize1FileSpan">請上傳圖片的大小不超過3MB</span> <input type='hidden' id='imgSize1' name='imgSize1' value='' reg="^.+$" tip="親!您忘記上傳產品圖片了。" /></p>
JS函數
function submitImgSize1Upload() {var option = {url:"${path}/upload/upload.do",//使用ajax的方式提交表單,url以option中為準type:'post',dataType:"text",//不要寫成dateTypedata:{fileName:'imgSize1File'},success:function(responseText){//把字串解析成json對象var obj = $.parseJSON(responseText);$("#imgSize1ImgSrc").attr("src", obj.realPath);$("#imgSize1").val(obj.relativePath);},error:function(){alert("系統錯誤");}};$("#myForm").ajaxSubmit(option);}
控制層:
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
@RequestMapping("/upload.do")public void upload(String fileName, HttpServletRequest request, PrintWriter out){MultipartHttpServletRequest mr = (MultipartHttpServletRequest) request;CommonsMultipartFile cfile = (CommonsMultipartFile) mr.getFile(fileName);byte[] fbyte = cfile.getBytes();String imageName = "";SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");imageName = format.format(new Date());Random random = new Random();for(int i =0; i < 3; i++){imageName = imageName + random.nextInt(10);}String raginalFileName = cfile.getOriginalFilename();String suffixName = raginalFileName.substring(raginalFileName.lastIndexOf("."));//建立用戶端Client client = Client.create();//圖片在圖片伺服器上的絕對路徑String imagePath = EcpsConstants.UPLOAD_PATH+"/upload/"+imageName+suffixName;WebResource resource = client.resource(imagePath);//把圖片放到圖片伺服器上resource.put(String.class, fbyte);String result = "{\"realPath\":\""+imagePath+"\", \"relativePath\":\""+"/upload/"+imageName+suffixName+"\"}";out.write(result);out.close();}
jsp+ajax+springMvc圖片上傳立刻回顯 電商