1.场景还原
近期,由于项目需求需要上传图片logo,笔者在探索的过程中遇到过很多坑,今晚就把个人经验分享出来尽量少让博友脑壳疼
2.准备工作
①选择一个专门存储图片的服务器,这里我选择了第三方七牛云存储,真心感觉不错!
②前端与后台采用Ajax交互
3.前端代码
①代码分析
File upload
upload function getUpload(){ var formData =newFormData();formData.append('file',$('#file')[0].files[0]);$.ajax({ url:'http://localhost:8080/qiniu/upload',type:'POST',dataType:"json",cache:false,data: formData,processData:false,contentType:false}).done(function(res) { alert(res.data);document.getElementById("img").src = res.data;}).fail(function(res) { alert("fail");});}
②重点分析
append()的第二个参数应是文件对象,即$('#file')[0].files[0]。contentType也要设置为‘false’。
从代码$('#file')[0].files[0]中可以看到一个标签能够上传多个文件,只需要在里添加multiple或multiple="multiple"属性。对了这里的dataType一定别忘了写json,不然会解析失败的。
③看效果
4.后台代码
①导入相关依赖
com.google.code.gsongson2.8.0com.squareup.okhttp3okhttp3.6.0com.squareup.okiookio1.11.0com.qiniuqiniu-java-sdk7.1.3commons-iocommons-io2.3commons-fileuploadcommons-fileupload1.2.2
②定义七牛上传图片并返回外链的方法
/*** Created by zhangxing on 2017/6/7.*/public classQiniuUpload {privateStringpicFile;privateStringpicUrl="";publicQiniuUpload(String path){picFile= path;}private static finalStringSPOT="http://om8czer7p.bkt.clouddn.com/";//baseUrl//设置好账号的ACCESS_KEY和SECRET_KEYStringACCESS_KEY="你的ACCESS_KEY";//这两个登录七牛 账号里面可以找到StringSECRET_KEY="你的SECRET_KEY";//要上传的空间Stringbucketname="zhangxing";//填写新建的那个存储空间对象的名称//上传到七牛后保存的文件名Stringkey=newDate().getTime()+".jpg";//上传文件的路径//String FilePath = "E:\\1.jpg"; //本地要上传文件路径//密钥配置Authauth= Auth.create(ACCESS_KEY,SECRET_KEY);//创建上传对象UploadManageruploadManager=newUploadManager();//简单上传,使用默认策略,只需要设置上传的空间名就可以了publicStringgetUpToken(){returnauth.uploadToken(bucketname);}//普通上传publicStringupload()throwsIOException {try{//调用put方法上传Response res =uploadManager.put(picFile,key,getUpToken());//打印返回的信息System.out.println(res.isOK());if(res.isOK()){picUrl=SPOT+key;System.out.println(picUrl);}else{ System.out.println("上传失败!");} System.out.println(res.bodyString());}catch(QiniuException e) { Response r = e.response;System.out.println(r.url());//请求失败时打印的异常的信息System.out.println(r.toString());try{//响应的文本信息System.out.println(r.bodyString());}catch(QiniuException e1) {//ignore} }returnpicUrl;} }
记住,这个方法返回的是图片访问的外链。
③配置spring-web
将上述代码原原本本贴在spring-web中
④上传的controller
@RestController@RequestMapping("qiniu")public classQinNiuControllerextendsBaseController {@RequestMapping(value="/upload",method= RequestMethod.POST)publicStringupload(HttpServletResponse response,@RequestParam("file") MultipartFile file)throwsIOException { response.setHeader("Access-Control-Allow-Origin","*");String fileName=file.getOriginalFilename();File targetFile=newFile("F:\\picture",fileName);if(!targetFile.exists()){ targetFile.mkdirs();}try{ file.transferTo(targetFile);}catch(Exception e){ e.printStackTrace();} String str =newQiniuUpload(targetFile.getAbsolutePath()).upload();//str得到的是一个七牛返回的外链,然后将str存到自己的服务器returnsuccess(str);}}
⑤BaseController
public classBaseController {protectedLoggerlog= LoggerFactory.getLogger(getClass());protectedLoggerbizErrorLog= LoggerFactory.getLogger("biz_log");private final staticThreadLocalrequest=newThreadLocal();private final staticThreadLocalresponse=newThreadLocal();protected finalIntegerDEFAULT_PAGE_SIZE=20;publicHttpServletRequestreq;publicHttpServletResponseresp;publicHttpSessionsession;@ModelAttributepublic voidreq(HttpServletResponse response,HttpServletRequest request){this.req= request;this.resp= response;this.session= request.getSession();}@SuppressWarnings("static-access")@ModelAttributepublic voidinit(finalHttpServletRequest request,finalHttpServletResponse response) {this.response.set(response);this.request.set(request);}protectedHttpServletRequestgetRequest() {returnrequest.get();}protectedHttpServletResponsegetResponse() {returnresponse.get();}@InitBinderprotected voidinitBinder(finalHttpServletRequest request,finalServletRequestDataBinder binder)throwsException { binder.addValidators(newParamValidator());}/***获取当前用户*/publicUsergetCurrentUser() { Authentication auth = SecurityContextHolder.getContext().getAuthentication();if(auth !=null) { Object principal = auth.getPrincipal();if(principalinstanceofUser) { User user = (User) principal;if(user !=null&& !user.isAnonymous() ) {returnuser;} }if(auth.getClass().getSimpleName().indexOf("Anonymous") <0) {log.error("Unknown authentication encountered, ignore it. "+ auth);} }throw newBizException(GlobalErrorCode.UNAUTHORIZED,"need login first.");}/***成功*/@SuppressWarnings({"rawtypes","unchecked"})publicStringsuccess(Object obj) { ResponseObject result =newResponseObject();result.setData(obj);String str = JSON.toJSONString(result);String callback = getRequest().getParameter("callback");if(!SysStringUtils.isEmpty(callback)) { str = callback+"("+str+")";returnstr;}returnstr;}publicStringchinaToUnicode(String str){ String result="";for(inti =0;i < str.length();i++){intchr1 = str.charAt(i);if(chr1>=19968&&chr1<=171941){//汉字范围\u4e00-\u9fa5 (中文)result+="\\u"+ Integer.toHexString(chr1);}else{ result+=str.charAt(i);} }returnresult;}@SuppressWarnings({"rawtypes","unchecked"})publicStringsuccess(Object obj,String score) { ResponseObject result =newResponseObject();result.setScore(score);result.setData(obj);returnJSON.toJSONString(result);}publicStringconvertToJsonp(String str) { String callback = getRequest().getParameter("callback");if(!SysStringUtils.isEmpty(callback)) { str = callback+"("+str+")";returnstr;}returnstr;}@SuppressWarnings({"rawtypes"})publicStringsuccess() { ResponseObject result =newResponseObject();returnJSON.toJSONString(result,SerializerFeature.WriteMapNullValue,SerializerFeature.WriteNonStringKeyAsString);}@SuppressWarnings({"rawtypes"})publicStringfail() { ResponseObject result =newResponseObject();returnJSON.toJSONString(result);}/***参数不正确*/@SuppressWarnings({"rawtypes"})publicStringargumentError(String msg) { ResponseObject result =newResponseObject(GlobalErrorCode.INVALID_ARGUMENT);result.setMoreInfo(msg);returnJSON.toJSONString(result);}/***逻辑错误*/publicStringerror(String msg) {throw newBizException(GlobalErrorCode.UNKNOWN,msg);}}
好了,走完整个流程看上传效果:
好了,七牛的图片外链就拿到了,然后记得存一把数据库。
csdn博客链接:http://blog.csdn.net/zhangxing52077/article/details/72935171