java后台跨域上传

时间:2022-02-09 17:06:01

前段时间在做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);

}

最后通过返回的图片路径,在本地显示。。