您的位置:首页 > 编程语言 > Java开发

java后台跨域上传

2016-12-19 17:10 183 查看
前段时间在做ajaxfileupload的跨域上传功能,因为是手机端的上传,所以不能使用swfupload插件,就用了ajaxfileupload的方式,但是跨域问题一直没有解决,所以就拐了个弯儿,先上传到本地,再在java的后台实现。具体代码如下:

private static final String url="http://XXXX";

public static String upload(String fileName,File file ) throws IOException{

HttpClient hc=HttpClients.createDefault();
HttpPost httpPost=new HttpPost(url);

MultipartEntityBuilder reqEntity =MultipartEntityBuilder.create();
reqEntity.addPart(fileName, new FileBody(file));

httpPost.setEntity(reqEntity.build());

HttpResponse response=hc.execute(httpPost);

HttpEntity entity = response.getEntity();
System.out.println(response.getStatusLine().getStatusCode());
String resultStr=null;
if(HttpStatus.SC_OK==response.getStatusLine().getStatusCode()){
if(entity!=null){
resultStr=EntityUtils.toString(entity, "GB2312");
}

System.out.println(resultStr);
}
return resultStr;
}

public static void main(String[] args) throws IOException {

String resultStr=upload("file001",new File("D:/Chrysanthemum.jpg"));

System.out.println(resultStr);

JSONObject json=JSONObject.fromObject(resultStr);

}

最后通过返回的图片路径,在本地显示。。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  跨域上传