尽量将要上传的文件放到最后,这样处理起来会简便一些,直接上代码,根据自己的需求截取代码片段。
jsp页面:
formclass="formform-h"id="form5"name="form5"enctype="multipart/form-data"method="post"action="/User/AppImport"fieldsetinputname="id"value="0"hidden="hidden"id="hiddenid"/divclass="f-gp"divclass="f-lb"labelclass="f-label"APP版本号:/label/divdivclass="f-ct"inputtype="text"value="1"class="f-textspan4"id="value"name="value"/div/divdivclass="f-gp"divclass="f-lb"labelclass="f-label"选择文件:/label/divdivclass="f-ct"inputtype="file"value=""class="f-textspan4"name="name"/div/divdivclass="diveder"/divdivclass="f-ac"aclass="btnbtn-mbtn-prim-g"href="javascript:void(0);"id="submit"上传/a/div/fieldset/form
java代码:
RequestMapping(value="/AppImport",method=RequestMethod.POST,produces="text/html;charset=utf-8")
ResponseBodypublicObjectAppImport(Integerid,Stringvalue,HttpServletRequestrequest){StringstrFilePath="";IntegernFileSize=0;booleanisMultipart=ServletFileUpload.isMultipartContent(request);if(isMultipart){ServletFileUploadupload=newServletFileUpload();upload.setHeaderEncoding("UTF-8");inti=0;try{FileItemIteratoriter=upload.getItemIterator(request);while(iter.hasNext()){i++;FileItemStreamfi=iter.next();InputStreamin=null;OutputStreamfileout=null;try{in=fi.openStream();ByteArrayOutputStreambstream=newByteArrayOutputStream();Streams.copy(in,bstream,true);if(fi.getFieldName().equalsIgnoreCase("id")){if(bstream.size()0){id=Integer.parseInt(String.valueOf(bstream));}}elseif(fi.getFieldName().equalsIgnoreCase("value")){if(bstream.size()0){value=String.valueOf(bstream);}}elseif(fi.getFieldName().equalsIgnoreCase("name")){strFilePath=fi.getName();nFileSize=bstream.size();StringstrUrl=String.format("/update/work-v%s.apk",value);if(id==)strUrl=String.format("/update/zjwork-v%s.apk",value);elseif(id==)strUrl=String.format("/update/ddwork-v%s.apk",value);StringstrLocalFile=request.getServletContext().getRealPath(strUrl);if(nFileSize0){Filefile=newFile(strLocalFile);fileout=newFileOutputStream(file);bstream.writeTo(fileout);}}}catch(IOExceptione){thrownewRuntimeException("filecopyerror!",e);}finally{if(in!=null){try{in.close();}catch(IOExceptione){e.printStackTrace();}}if(fileout!=null){try{fileout.close();}catch(IOExceptione){e.printStackTrace();}}}}}catch(Exceptione){thrownewRuntimeException("uploadfileerror.",e);}}else{//不支持文件上传}if(nFileSize==0){returnReturnWithAlert("请选择要上传的文件!",request);}else{SessionManagersm=newSessionManager(request);ClientServicesclient=newClientServices(sm.getTokenId());ClientServices.enumErrorCodeenumRet=client.UpdateSystemParameter(ClientServices.enumSystemParameter.FromInt(id),value);if(enumRet==ClientServices.enumErrorCode.enumSuccess)returnReturnWithAlert(String.format("上传APP成功,版本号%s",value),request);elsereturnReturnWithAlert(String.format("上传%s失败,可能当前用户无权上载!",strFilePath),request);}}