跨域上传图片Demo及分析

技术选型: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 ) ;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值