日期:2014-05-16  浏览次数:20476 次

jsp中使用xhEditor上传文件
public ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response)
        throws Exception
    {
        BufferedInputStream fileIn = new 
        BufferedInputStream(request.getInputStream()); 
        String fn = request.getParameter("filename");
        
        byte[] buf = new byte[1024];
        File file = new File("d:/" + fn); 
          
        BufferedOutputStream fileOut = new BufferedOutputStream(new 
        FileOutputStream(file)); 
          
        while (true) { 
            // 读取数据
            int bytesIn = fileIn.read(buf, 0, 1024); 
            System.out.println(bytesIn); 
            if (bytesIn == -1) 
            { 
                break; 
            } 
            else 
            { 
                fileOut.write(buf, 0, bytesIn); 
            } 
        } 
          
        fileOut.flush(); 
        fileOut.close(); 
        System.out.println(file.getAbsolutePath());
        //uploadFile(request);
        response.getWriter().println("{\"err\":\"\",\"msg\":\"" + file.getAbsolutePath() + "\"}");
        return null;
    }

?

我在spring中添加上面的方法;

?

?

在xheditoer源码作了小小改动,添加一个参数把文件名传到服务器去:

function postFile(fromfile,toUrl,callback,onProgress)
		{
			xhr = new XMLHttpRequest(),upload=xhr.upload;
			xhr.onreadystatechange=function(){if(xhr.readyState===4)callback(xhr.responseText);};
			if(upload)upload.onprogress=function(ev){onProgress(ev.loaded);};
			else onProgress(-1);//不支持进度
			if(toUrl.indexOf("&") == -1 && (toUrl.indexOf("?") == -1)){
				toUrl += "?filename="+fromfile.fileName
			}else{
				toUrl += "&filename="+fromfile.fileName;
			}


			xhr.open("POST", toUrl);
			xhr.setRequestHeader('Content-Type', 'application/octet-stream');
			xhr.setRequestHeader('Content-Disposition', 'attachment; name="'+inputname+'"; filename="'+fromfile.fileName+'"');
			if(xhr.sendAsBinary)xhr.sendAsBinary(fromfile.getAsBinary());
			else xhr.send(fromfile);
		}

?

这个就可以FF中使用html5特用的Ajax上传文件传文件了

?

原来一直认为只能表单提交方式上传文件,现在该改一下了,哈哈

?

?

?