import sun.misc.BASE64Decoder;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class MyWebServer {
public static void main(String[] args) {
try {
ServerSocket ss=new ServerSocket(8080);
while(true){
Socket socket=ss.accept();
BufferedReader bd=new BufferedReader(new InputStreamReader(socket.getInputStream()));
/**接受HTTP请求*/
String requestHeader;
int contentLength=0;
while((requestHeader=bd.readLine())!=null&&!requestHeader.isEmpty()){
/**获得POST参数1.获取请求内容长度*/
if(requestHeader.startsWith("Content-Length")){
int begin=requestHeader.indexOf("Content-Lengh:")+"Content-Length:".length();
String postParamterLength=requestHeader.substring(begin+1).trim();
contentLength=Integer.parseInt(postParamterLength);
}
}
OutputStream outputStream=socket.getOutputStream();//获取一个输出流,向服务端发送信息
String redCode="1";
PrintWriter printWriter=new PrintWriter(outputStream);//将输出流包装成打印流
printWriter.print(redCode);
printWriter.flush();
socket.shutdownOutput();//关闭输出流
StringBuffer sb=new StringBuffer();
if(contentLength>0) {
for (int i =0; i < contentLength; i++) {
sb.append((char) bd.read());
}
System.out.println("接收到的数据是:"+sb);
String imgName = sb.substring(14,36);
System.out.println("照片名字是:"+imgName);
String str = sb.toString().substring(49);
str = str.replace("%2F","/");
String str1 = str.replace("%252B","+");
String str2 = str1.replace("%3D","=");
bd.close();
socket.close();
System.out.println("接收到的base64数据是:"+str2);
String imgStr=str2.toString();
GenerateImage(imgStr,imgName);
}
}
}catch (IOException e) {
e.printStackTrace();
}
}
public static boolean GenerateImage(String imgStr,String imgName){//对字节数组字符串进行Base64解码并生成图片
if (imgStr ==null)//图像数据为空
return false;
BASE64Decoder decoder =new BASE64Decoder();
try {//Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i
{
if(b[i]<0) {//调整异常数据
b[i]+=256;
}
}
//生成jpg图片
String imgFilePath ="d://tupian/"+imgName+".jpg";//新生成的图片
OutputStream out =new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return true;
}catch (Exception e) {
return false;
}
}
}
效果如图: