JAVA信息传送代码之下载图片

文章详细描述了如何使用JAVA编程语言创建一个简单的客户端和服务端,通过ServerSocket和Socket进行图片下载,展示了文件流的使用。

JAVA信息传送代码之下载图片

package xin.week1.day3;
import org.junit.Test;

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

/*首先开启客户端服务
* 客户端下载服务端侧的图片*/

public class tcpxiazai {

    @Test
    public void server() {
        ServerSocket ss = null;
        Socket socket = null;
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            ss = new ServerSocket(9090);    //定义端口
            socket = ss.accept();
            fis = new FileInputStream(new File("Java.jpg"));    //客户端图片
            os = socket.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = fis.read(b)) != -1) {
                os.write(b, 0, len);
            }
            socket.shutdownOutput();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (os != null) {
                try {
                    os.close();
                } catch (IOException e) {
// TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
// TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
// TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (ss != null) {
                try {
                    ss.close();
                } catch (IOException e) {
// TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }}


    //客户端
    @Test
    public void client() {
        Socket socket1 = null;
        FileOutputStream fos = null;
        InputStream is = null;
        try {
            //匹配服务端IP+端口
            socket1 = new Socket(InetAddress.getByName("127.0.0.1"), 9090);
            //图片下载位置
            fos = new FileOutputStream(new File("E:\\lj\\Java.jpg"));
            is = socket1.getInputStream();
            byte[] b = new byte[1024];
            int len;
            while ((len = is.read(b)) != -1) {
                fos.write(b, 0, len);
            }
            System.out.println("下载成功");
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
// TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    is.close();
                } catch (IOException e) {
// TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (fos != null) {
                try {
                    socket1.close();
                } catch (IOException e) {
// TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
}

在这里欢迎大家的点赞、关注、评论,以此来促进大家互相学习交流,同时可以让新加入的小伙伴更快的了解新知识!!!

文章内容如有侵权,请联系作者进行删除

≧◠◡◠≦ 1分2分都是爱,感谢已经打赏的老板,和正在打赏的老板们 ≧◠◡◠≦

Java 中实现将前端传送图片存储到本地,通常可以使用 Spring Boot 框架结合 Servlet 的 `MultipartFile` 类来完成。以下是具体步骤和示例代码: ### 1. 添加依赖 如果使用 Maven 项目,需要在 `pom.xml` 中添加 Spring Boot Web 依赖: ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies> ``` ### 2. 创建控制器 创建一个 Spring Boot 控制器来处理前端传来的图片并保存到本地: ```java import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @RestController public class ImageUploadController { @PostMapping("/uploadImage") public String uploadImage(@RequestParam("image") MultipartFile file) { if (file.isEmpty()) { return "上传的文件为空"; } try { // 获取文件的字节数组 byte[] bytes = file.getBytes(); // 指定保存的目录 String uploadDir = "uploads"; File dir = new File(uploadDir); if (!dir.exists()) { dir.mkdirs(); } // 构建文件保存路径 Path path = Paths.get(uploadDir + File.separator + file.getOriginalFilename()); // 将文件写入指定路径 Files.write(path, bytes); return "文件上传成功,保存路径:" + path.toString(); } catch (IOException e) { e.printStackTrace(); return "文件上传失败:" + e.getMessage(); } } } ``` ### 3. 启动 Spring Boot 应用 创建一个 Spring Boot 主类来启动应用: ```java import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class ImageUploadApplication { public static void main(String[] args) { SpringApplication.run(ImageUploadApplication.class, args); } } ``` ### 代码解释 - **依赖**:引入 Spring Boot Web 依赖以使用 Web 相关功能。 - **控制器**:`ImageUploadController` 类中的 `uploadImage` 方法处理前端传来的图片。首先检查文件是否为空,然后获取文件的字节数组,指定保存目录并创建目录(如果不存在),最后将文件写入指定路径。 - **主类**:`ImageUploadApplication` 类用于启动 Spring Boot 应用。 ### 前端测试 可以使用 HTML 表单来测试图片上传功能: ```html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>图片上传</title> </head> <body> <form action="http://localhost:8080/uploadImage" method="post" enctype="multipart/form-data"> <input type="file" name="image"> <input type="submit" value="上传"> </form> </body> </html> ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

TinyTuiKun

感谢各位老板们的打赏

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值