自定义一个图片上传服务器
需求分析
读取用户上传的文件信息,判断是否是图片格式 建立一个文件夹,存储这些文件,文件名按照一定格式存储 应设置一个最大上传大小,若文件大于最大值,不予上传 为了可以实现多用户的上传,使用多线程
代码实现
1.设置一个文件判断函数,方便调用
public static String bytesToHexString ( byte [ ] src) {
StringBuilder stringBuilder = new StringBuilder ( ) ;
if ( src == null || src. length <= 0 ) {
return null;
}
for ( int i = 0 ; i < src. length; i++ ) {
String hv = Integer. toHexString ( src[ i] & 0xFF ) . toUpperCase ( ) ;
if ( hv. length ( ) < 2 ) {
stringBuilder. append ( 0 ) ;
}
stringBuilder. append ( hv) ;
}
return stringBuilder. toString ( ) ;
}
public static String checkType ( String fileTypeHead) {
switch ( fileTypeHead) {
case "FFD8FF" : return "jpg" ;
case "89504E47" : return "png" ;
case "47494638" : return "gif" ;
case "49492A00" : return "tif" ;
case "424D" : return "bmp" ;
default : return null;
}
}
2.创建一个服务器,用来接收客户端上传的文件
ServerSocket ss = new ServerSocket ( 10000 ) ;
Socket s = ss. accept ( ) ;
String ip = s. getInetAddress ( ) . getHostAddress ( ) ;
InputStream in = s. getInputStream ( ) ;
byte [ ] buf = new byte [ 1024 ] ;
int len = in. read ( buf) ;
String text = new String ( buf, 0 , len) ;
System. out. println ( text) ;
3.应要实现多用户上传,所以应该将读取流封装到一个类中并实现Runable接口。
@SuppressWarnings ( "resource" )
ServerSocket ss = new ServerSocket ( 10000 ) ;
while ( true ) {
Socket s = ss. accept ( ) ;
new Thread ( new MyTask ( s) ) . start ( ) ;
}
private Socket s;
public MyTask ( Socket s) {
this . s = s;
}
@Override
public void run ( ) {
try {
InputStream in = s. getInputStream ( ) ;
FileOutputStream fos = new FileOutputStream ( file) ;
byte [ ] buf = new byte [ 1024 ] ;
int len = 0 ;
while ( ( len = in. read ( buf) ) != - 1 ) {
fos. write ( buf, 0 , len) ;
}
OutputStream out = s. getOutputStream ( ) ;
out. write ( "上传成功" . getBytes ( ) ) ;
fos. close ( ) ;
s. close ( ) ;
} catch ( IOException e) {
}
4.添加健壮性判断,设置文件最大上传大小以及文件存储格式
private static final int SIZE = 1024 * 1024 * 2 ;
InputStream in = s. getInputStream ( ) ;
byte [ ] b = new byte [ 3 ] ;
in. read ( b, 0 , b. length) ;
String fileTypeHead = FileEquals. bytesToHexString ( b) ;
String fileType = FileEquals. checkType ( fileTypeHead) ;
if ( ! ( fileType == null) ) {
File dir = new File ( "d:\\dir" ) ;
if ( ! dir. exists ( ) ) {
dir. mkdirs ( ) ;
}
File file = new File ( ip + "." + fileType) ;
if ( file. exists ( ) ) {
file = new File ( ip + ( ++ count) + "." + fileType) ;
}
FileOutputStream fouts = new FileOutputStream ( file) ;
byte [ ] buf = new byte [ 1024 ] ;
int len = 0 ;
while ( ( len = in. read ( buf) ) != - 1 ) {
fouts. write ( buf, 0 , len) ;
if ( file. length ( ) > SIZE) {
System. out. println ( "文件过大,无法按上传!" ) ;
fouts. close ( ) ;
s. close ( ) ;
file. delete ( ) ;
return ;
}