通过WebService上传文件的原理
我们都知道如何通过WebService把一个字符串形式的参数传递到服务器端的一个函数并取得返回的结果,而通过WebService上传文件的原理和上传一个字符串在根本上是一样的。
唯一不同的是,我们需要多做一点额外的工作,即先读取文件到一个字节数组中,再通过Base64将其转化为字符串。详情请看下面的代码: //?客户端读取文件然后用Base64将其转化为字符串的函数 private?static?String?getFileByteString(File?file)?throws?Exception{ ????InputStream?in?=?new?FileInputStream(file); ? ????//?取得文件大小 ????long?length?=?file.length(); ? ????//?根据大小创建字节数组 ????byte[]?bytes?=?new?byte[(int)?length]; ? ????//?读取文件内容到字节数组 ????int?offset?=?0; ????int?numRead?=?0; ????while?(offset?<?bytes.length ????????&&?(numRead?=?in.read(bytes,?offset,?bytes.length?-?offset))?>=?0)?{ ??????offset?+=?numRead; ????} ? ????//?读取完毕的校验?? ????if?(offset?<?bytes.length)?{ ??????throw?new?IOException("不能完全讀取文件:"+?file.getName()); ????} ? ????in.close(); ? ????String?encodedFileString?=?Base64.encode(bytes); ? ????return?encodedFileString; }
byte[]?bytes?=?Base64.decode(uploadedFileString); ???????????? //?存储路径 String?path=CommonUtil.getUploadPath(); //?存储的文件名 String?localFileName=getLocalFileName(parser.getUserid(),parser.getFileName()); //?写入新文件 FileOutputStream?out?=?new?FileOutputStream(path+localFileName); out.write(bytes); out.flush(); out.close();
????private?static?final?long?serialVersionUID?=?-7444606086930580188L; ????public?void?doPost(HttpServletRequest?request,?HttpServletResponse?response) ????????????throws?ServletException,?java.io.IOException?{ ????} ????public?void?doGet(HttpServletRequest?request,?java.io.IOException?{ ????????doPost(request,?response); ????} ????public?void?init(ServletConfig?config)?throws?ServletException?{ ??????? ????????//?设置上传路径 ????????CommonUtil.setUploadPath(config.getServletContext().getRealPath("/")); ????} }
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- 『AngularJS』创建 Service
- webservice 两种消息格式 SoapDocumentProtocol,SoapRpcPr
- angularjs – svg的无效值
- 【WebService学习过程记录(三)】XFire开发Web Service---He
- Webservice soap wsdl区别之个人见解
- Bash选项卡完成后,会在第一个完成后添加额外的空间
- angularjs – Bootstrap和Foundation与MVC框架的集成
- twitter-bootstrap – Twitter Bootstrap中的Font Awesome
- Scala元组内存开销
- bash – 当目录名称中包含空格时使用查找结果