标签: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>
function submitImgSize1Upload() { var option = { url:"${path}/upload/upload.do",//使用ajax的方式提交表单,url以option中为准 type:'post', dataType:"text",//不要写成dateType data:{ 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+springmvc图片上传立刻回 ssh spring 异步
原文地址:http://blog.csdn.net/ojackhao/article/details/45190049