当前位置: 首页 > 工具软件 > AjaxUpload > 使用案例 >

文件上传二之ajaxupload

佟和平
2023-12-01

一.引入ajaxfileuploadjs文件

文件引用下载路径:点击打开链接

二.前台html代码

<span style="font-size:14px;"><span style="font-size:14px;"> <body>
	<h1>选择图片后,点击按钮上传</h1>
	<input id="fileToUpload" type="file" size="45" name="fileToUpload"
		class="input">
	<button class="button" οnclick="ajaxFileUpload()">上传</button>
	<br>
<!-- 	<img id="viewImg"> -->
  </body></span></span>

三.前台js代码

<span style="font-size:14px;"><span style="font-size:14px;">function ajaxFileUpload() {
		$.ajaxFileUpload({
			type:'POST',
			url : 'saveAllAddressInfo',
			secureuri : false,
			fileElementId : 'fileToUpload',     //与html代码中的input的id值对应
			dataType : 'json',
			data : {username : "tom"},
			success : function(data, status) {
			alert(status);
			alert(data.result);
// 				$('#viewImg').attr('src',data.picUrl);
			},
			error : function(data, status, e) {
				alert('上传出错');
			}
		})
	}</span></span>

四.后台java代码

<span style="font-size:14px;"><span style="font-size:14px;">@RequestMapping(value="saveAllAddressInfo")
	public @ResponseBody HashMap<String,Object> saveAllAddressInfo(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException{
		HashMap<String,Object> dataMap = new HashMap<String,Object>();
//		dataMap.put("result", Constant.ERROR);
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;   
		 	String adAddName=request.getParameter("adAddName");
	        /**构建图片保存的目录**/    
	        String logoPathDir = "/upload";     
	        /**得到图片保存目录的真实路径**/    
	        String logoRealPathDir = request.getSession().getServletContext().getRealPath(logoPathDir);     
	        /**根据真实路径创建目录**/    
	        File logoSaveFile = new File(logoRealPathDir);     
	        if(!logoSaveFile.exists())    
	            logoSaveFile.mkdirs();           
	        /**页面控件的文件流**/    
	        MultipartFile multipartFile = multipartRequest.getFile("fileToUpload");    //此fileToUpload与前台对应
	        System.out.println(multipartFile.getOriginalFilename());
	        /**获取文件的后缀**/    
//	        String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));     
//	        /**使用UUID生成新的文件名称**/    
//	        String logImageName = UUID.randomUUID().toString()+ suffix;//构建文件名称     
	        String logImageName = multipartFile.getOriginalFilename().substring(0,multipartFile.getOriginalFilename().lastIndexOf("."))
	        		             +"_"+UUID.randomUUID().toString()
	        		             +multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));  
	        /**拼成完整的文件保存路径加文件**/    
	        String fileName = logoRealPathDir + File.separator + logImageName;                
	        File file = new File(fileName);            
	        try {     
	            multipartFile.transferTo(file);     
	        } catch (IllegalStateException e) {     
	            e.printStackTrace();     
	        } catch (IOException e) {            
	            e.printStackTrace();     
	        }   
	        dataMap.put("result", Constant.OK);
		    return dataMap;	
	}</span></span>

五,处理返回json结果值异常问题

我后台判读ajaxfileupload成功的标志,result为1,在前台一直显示错误,我在源码里断点

<span style="font-size:14px;"><span style="font-size:14px;">uploadHttpData: function( r, type ) {
    var data = !type;
    data = type == "xml" || data ? r.responseXML : r.responseText;
    // If the type is "script", eval it in global context
    if ( type == "script" )
        jQuery.globalEval( data );
    // Get the JavaScript object, if JSON is used.
    if ( type == "json" ) {
          eval( "data = " + data);
    }
    // evaluate scripts within html
    if ( type == "html" )
        jQuery("<div>").html(data).evalScripts();
    return data;
}</span></span>
然后看到调试里显示r.responseText 值是这样的<pre>{"result":"1"}</pre>我到是奇怪了,服务器明明返回的是json数据,但是捕获到的确是json数据被<pre>包含,

具体什么原因不太清楚,于是直接在里面给过滤掉,修改代码如下:

<span style="font-size:14px;"><span style="font-size:14px;">uploadHttpData: function( r, type ) {
    var data = !type;
    data = type == "xml" || data ? r.responseXML : r.responseText;
    // If the type is "script", eval it in global context
    if ( type == "script" )
        jQuery.globalEval( data );
    // Get the JavaScript object, if JSON is used.
    if ( type == "json" ) {
         以下为新增代码///
         data = r.responseText;
         var start = data.indexOf(">");
         if(start != -1) {
           var end = data.indexOf("<", start + 1);
           if(end != -1) {
             data = data.substring(start + 1, end);
            }
         }
          ///以上为新增代码///
          eval( "data = " + data);
    }
    // evaluate scripts within html
    if ( type == "html" )
        jQuery("<div>").html(data).evalScripts();
    return data;
}</span></span>




 类似资料: