技术选型:nginx中配置跨域支持功能
配置代码:
在nginx.conf中配置
http { add_header Access -Control -Allow -Origin *; add_header Access -Control -Allow -Headers X -Requested -With ; add_header Access -Control -Allow -Methods GET,POST,OPTIONS ; }这样就可以实现GET,POST,OPTIONS的跨域请求的支持 也可以 add_header Access-Control-Allow-Origin http://test.51testing.com; –指定允许的url;
应用环境:基于springBoot微服务/spring框架服务
技术选型:采用jQuery File Upload Plugin插件提交(GIT地址:https://github.com/blueimp/jQuery-File-Upload)
上传图片DEMO地址:https://github.com/mijingling/springBoot-fileupload
核心代码:
前端:
<input id = "fileupload" type = "file" name = "imgUpload" > <script src = "util/jquery.1.9.1.min.js" ></script > <script src = "plugins/js/vendor/jquery.ui.widget.js" ></script > <script src = "plugins/js/jquery.iframe-transport.js" ></script > <script src = "plugins/js/jquery.fileupload.js" ></script > <script > $ ( function ( ) { //上传 $ ( '#fileupload' ). fileupload ( { xhrFields : { crossDomain : true , withCredentials : true } , url : "http://localhost:8099/jquery/cross/xmlupload" , multiple : false , type : "POST" , dataType : 'json' , done : function (e , data ) { if (data. result. code == "success" ) { var fullImgPath = "http://localhost:8099/" +data. result. imgPath ; $ ( "#imgShow" ). attr ( "src" ,fullImgPath ) ; $ ( "#imgHref" ). attr ( "href" ,fullImgPath ) ; $ ( "#imgLabel" ). html (fullImgPath ) ; $ ( "#resultCode" ). html (data. result. code ) ; } } } ) ; } ) ; </script >后端:
/** * jquery图片上传-跨域-XMLHttpRequest提交 */ @CrossOrigin @RequestMapping (value = "/jquery/cross/xmlupload", method = RequestMethod. POST ) public String jqueryCross (HttpServletRequest request, HttpServletResponse response ) { Map < String, String > rsMap = new HashMap <> ( ) ; MultipartFile multipartFile = ( (MultipartHttpServletRequest ) request ). getFile ( "imgUpload" ) ; String fileName = multipartFile. getOriginalFilename ( ) ; String suffix = fileName. substring (fileName. lastIndexOf ( "." ) ) ; // 文件后缀 // key 以文件以时间命名,根据上传文件名取后缀 String objectkey = "upload/" + System. currentTimeMillis ( ) + suffix ; File file = new File ( "src/main/webapp/" +objectkey ) ; try { FileUtils. copyInputStreamToFile (multipartFile. getInputStream ( ), file ) ; } catch ( IOException e ) { rsMap. put ( "code", "failed" ) ; System. out. println ( "接收图片出错" ) ; return JSON. toJSONString (rsMap ) ; } //组装上传结果 rsMap. put ( "code", "success" ) ; rsMap. put ( "imgPath", objectkey ) ; return JSON. toJSONString (rsMap ) ; }