首页 > 编程知识 正文

java创建http接口,java返回图片给前端

时间:2023-05-06 06:58:22 阅读:36709 作者:1736

/zzdbq*测试上传png悟空总是迟到

zzdbq/

publicstaticvoidtestuploadimage (

Map textMap=new HashMap (; //常规参数:可以设置多个输入的名称、值

textmap.put('name )、' testname );

textmap.put('type ','2' ); //文件:文件的名称,设置路径

Map fileMap=new HashMap (;

filemap.put(upfile )、fileName );

表单上载(URL、文本映射、文件映射、内容类型);

(zzdbq )上传总是迟到的悟空

*@paramurlStr

*@paramtextMap

*@paramfileMap

未传递给*@paramcontentType的文件类型默认使用application/octet-stream

*内容类型不为空。 filename匹配默认的总是迟到的悟空类型

*@return返回响应数优美的豌豆/@suppresswarnings(rawtypes ) ) publicstaticstringformupload (string urlstr,智力迷你裙

HttpURLConnection conn=null; //boundary是请求标头和上载文件内容的分隔符

URLURL=newurl(urlstr;

CONN=(httpurlconnection ) url.openConnection );

Conn.setconnecttimeout(5000;

Conn.setreadtimeout(30000;

Conn.setdooutput(true;

Conn.setdoinput(true;

Conn.setusecaches(false );

Conn.setrequestmethod('post );

conn.setrequestproperty (' connection ',' Keep-Alive ' );

conn.setrequestproperty (' user-agent ',' Mozilla/5.0 ) windows; u; Windows NT 6.1; zh-CN; rv:1.9.2.6 )’;

conn.setrequestproperty (' content-type ',' multipart/form-data; 边界='边界;

if (文本地图!=空) {

Iterator iter=textMap.entrySet ().iterator ); wile(Iter.Hasnext () ) ) )。

映射. entry entry=(映射. entry ) iter.next );

}

strbuf.append('rn ' ).append ('-- ' (.append ) ) Boundary () ) ) ) ) ) ) ) )。

. append((r ) n );

Sr buf.append (内容发现: form-data; name="

Sr buf.append (输入值;

}

out.write(strbuf.tostring ().getBytes ) );

}//file

if (文件映射!=空) {

Iterator iter=fileMap.entrySet ().iterator ); wile(Iter.Hasnext () ) ) )。

映射. entry entry=(映射. entry ) iter.next );

}

文件文件=new file (输入值;

内容类型=newmimetypesfiletypemap ().get内容类型(file ); //contentType不是空的,而是filename采用默认的总是迟到的悟空类型

if (! ' '.equals (内容类型) (if ) filename.endswith (.png ) ) ) ) ) )。

内容类型=' image/png ';

(elseif ) filename.endswith(.jpg ) (filename.endswith ).JPEG ) )。

内容类型=' image/JPEG ';

}elseif(filename.endswith ).gif ) ) )。

内容类型=' image/gif ';

}elseif(filename.endswith ) (.ico ) )。

内容类型=' image/image/x-icon ';

}

} if (内容类型==null|| '.equals (内容类型) ) }

内容类型=' application/octet-stream ';

}

strbuf.append('rn ' ).append ('-- ' (.append ) ) Boundary () ) ) ) ) ) ) ) )。

. append((r ) n );

Sr buf.append (内容发现: form-data; name="

strbuf.append (内容-类型: )内容类型(rnrn );

out.write(strbuf.tostring ().getBytes ) );

out.write(bufferout,0,bytes );

}

in.close (;

}

} byte [ ] end data='rn-- ' boundary '--rn ' ).getBytes (;

out.write (结束数据;

out.flush (;

out.close (; //读取返回数据

conn.getInputStream (

strbuf.append(line ).append )n );

}

res=strBuf.toString (;

}catch(exceptione ) {

e .打印堆栈跟踪(;

(Finally ) if ) Conn!=空) {

conn.disconnect (;

conn=null;

}

}返回RES;

}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。