JAVA-IO多线程图片上传


关键在于需要熟悉各种流的操作,上传文本或者图片或者视频的区别都在于输入输出流的不同,这是IO部分的内容。

自身在IO部分基础不是特别牢靠,还需要深入了解。

服务端

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class PicUploadServer {
    public static void main(String[] args) {
        try {
            ServerSocket ss = new ServerSocket(23333);
            while (true) {
                Socket s = ss.accept();
                //每当有客户端上传图片,开启一个线程处理
                new Thread(new PicDealThread(s)).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class PicDealThread implements Runnable {
    private Socket s;

    PicDealThread(Socket s) {
        this.s = s;
    }

    @Override
    public void run() {
        try {
            //利用ip地址作为图片文件名
            int index = 1;
            String ip = s.getInetAddress().getHostAddress();
            File file = new File(ip + ".jpg");
            //如果存在同名图片,使用数字后缀,直到不重名
            while (file.exists()) {
                file = new File(ip + "(" + (index++) + ")" + ".jpg");
            }
            //输出流,用于存储图片
            BufferedOutputStream bufos = new BufferedOutputStream(new FileOutputStream(file));
            byte[] buf = new byte[1024];
            int len;
            InputStream in = s.getInputStream();
            while ((len = in.read(buf)) != -1) {
                bufos.write(buf, 0, len);
            }
            PrintWriter pw = new PrintWriter(s.getOutputStream(), true);
            pw.println("上传图片成功!");
            bufos.close();
            in.close();
            s.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

客户端

import java.io.*;
import java.net.Socket;

public class PicUploadClient {
    public static void main(String[] args) {
        try {
            //通过输入路径选择图片
            BufferedReader bufr = new BufferedReader(new InputStreamReader(System.in));
            String fileName = bufr.readLine();
            File file = new File(fileName);

            //必要的检测
            if (!(file.exists() && file.isFile())) {
                System.err.println("并不是一个文件!");
                return;
            }
            if (!file.getName().endsWith("jpg")) {
                System.err.println("图片格式错误,请重新选择!");
                return;
            }
            if (file.length() > 1024 * 1024 * 5) {
                System.err.println("图片大小不得超过5M!");
                return;
            }
            //连接服务器
            Socket s = new Socket("192.168.149.1", 23333);
            //读取文件
            BufferedInputStream bufIn = new BufferedInputStream(new FileInputStream(fileName));
            //用于向服务器写入字节的输出流
            OutputStream out = s.getOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = bufIn.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            //关闭输出流,即上传完毕
            s.shutdownOutput();
            //获取服务器反馈信息
            String info;
            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            info = in.readLine();
            System.out.println(info);
            buf.clone();
            bufIn.close();
            s.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

END

Java中使用多线程上传文件可以提高上传速度和效率。下面是一个简单的示例代码,演示了如何使用多线程上传文件: ```java import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class FileUploader implements Runnable { private String url; private File file; public FileUploader(String url, File file) { this.url = url; this.file = file; } @Override public void run() { try { uploadFile(); } catch (IOException e) { e.printStackTrace(); } } private void uploadFile() throws IOException { HttpURLConnection connection = null; FileInputStream inputStream = null; OutputStream outputStream = null; try { URL uploadUrl = new URL(url); connection = (HttpURLConnection) uploadUrl.openConnection(); connection.setDoOutput(true); connection.setRequestMethod("POST"); inputStream = new FileInputStream(file); outputStream = connection.getOutputStream(); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { System.out.println("文件上传成功"); } else { System.out.println("文件上传失败"); } } finally { if (connection != null) { connection.disconnect(); } if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } } ``` 使用示例: ```java public class Main { public static void main(String[] args) { String url = "http://example.com/upload"; File file = new File("path/to/file"); FileUploader uploader = new FileUploader(url, file); Thread thread = new Thread(uploader); thread.start(); } } ``` 在上述示例中,FileUploader类实现了Runnable接口,并在run()方法中执行文件上传的逻辑。在uploadFile()方法中,首先创建URL对象并打开连接,然后设置请求方法为POST,并将文件内容通过输出流写入到服务器。最后,根据服务器的响应码判断上传是否成功。 通过创建多个FileUploader对象,并将其放入不同的线程中运行,可以实现多线程上传多个文件。每个线程独立处理一个文件的上传任务,从而提高上传速度和效率。 请注意,这只是一个简单的示例,实际应用中可能还需要处理异常、添加进度监控等功能。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值