jsp+ajax+springMvc圖片上傳立刻回顯 電商

來源:互聯網
上載者:User

標籤: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圖片上傳立刻回顯 電商

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.