The examples in this article share the Java image upload code for your reference. The specific content is as follows
import java.io.*; import java.net.*; /* *Send end*/ class picsend { public static void main(String[] args) throws Exception { if(args.length!=1) { System.out.println("Please select a .jpg picture"); return; } File file = new File(args[0]); if (!(file.exists() && file.isFile())) { System.out.println("There is a problem with the picture (not a file or does not exist)"); return; } if(!file.getName().endsWith(".jpg")) { System.out.println("The picture format is wrong, please reselect the picture"); return; } if(file.length()>1024*1024*10) { System.out.println("The picture is too large and cannot be uploaded"); return; } Socket s = new Socket("192.168.33.1",10006);//Create a service FileInputStream fis = new FileInputStream("d://beauty.jpg");//Read the picture OutputStream out = s.getOutputStream();//Readed write byte [] b = new byte[1024]; int len = 0; while((len = fis.read(b))!= -1) { out.write(b,0,len); } s.shutdownOutput();//Tag end InputStream in = s.getInputStream();//Read server returns data byte [] bin = new byte[1024]; int num = in.read(bin); System.out.println(new String(bin,0,num)); fis.close(); s.close(); } } class picThread implements Runnable { private Socket s; picThread(Socket s) { this.s = s; } public void run() { int count = 1; String ip = s.getInetAddress().getHostAddress();//Get ip try { System.out.println(ip+"..........connect"); InputStream in = s.getInputStream();//Read the data in the stream File file = new File(ip+"("+(count)+")"+".jpg"); while(file.exists())//Determine whether the file exists file = new File(ip+"("+(count++)+")"+".jpg"); FileOutputStream fos = new FileOutputStream(file);//Write byte [] b = new byte[1024]; int len = 0; while((len = in.read(b))!=-1) { fos.write(b,0,len); } OutputStream out = s.getOutputStream();//Write data transmitted to the server out.write("Uploaded successfully! ".getBytes()); fos.close(); s.close(); } catch (Exception e) { throw new RuntimeException("Upload failed"); } } } /* *Server*/ class picrece { public static void main(String[] args) throws Exception { ServerSocket ss = new ServerSocket(10006); while(true) { Socket s = ss.accept();//Receive new Thread(new picThread(s)).start(); } } }Effect:
The above is all about this article, I hope it will be helpful for everyone to learn Java programming.