栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

[2021-11-04] 使用Java原生Http实现同时上传多个文件以及文件下载功能

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

[2021-11-04] 使用Java原生Http实现同时上传多个文件以及文件下载功能

使用Java原生Http实现同时上传多个文件以及文件下载功能

首先创建两个Spring Boot项目,一个用作客户端发送Http请求,一个用作服务端接受Http请求并将文件保存至数据库中


pom.xml文件如下
服务端:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.6
         
    
    com.hk
    httpServer
    0.0.1-SNAPSHOT
    httpServer
    httpServer
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-starter-web
        
        
            com.baomidou
            mybatis-plus-boot-starter
            3.4.3.4
        
        
            com.baomidou
            mybatis-plus-generator
            3.4.1
        

        
            com.baomidou
            mybatis-plus
            3.4.3.4
        

        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        
        
            mysql
            mysql-connector-java
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
        
            org.springframework.boot
            spring-boot-starter-data-jpa
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    



客户端:



    4.0.0
    
        org.springframework.boot
        spring-boot-starter-parent
        2.5.6
         
    
    com.hk
    httpClient
    0.0.1-SNAPSHOT
    httpClient
    httpClient
    
        1.8
    
    
        
            org.springframework.boot
            spring-boot-devtools
            runtime
            true
        
        
            org.projectlombok
            lombok
            true
        
        
            org.springframework.boot
            spring-boot-starter-test
            test
        
    

    
        
            
                org.springframework.boot
                spring-boot-maven-plugin
                
                    
                        
                            org.projectlombok
                            lombok
                        
                    
                
            
        
    



编写客户端发送Http请求的代码,需要用到

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

上传文件方法代码:

public static String uploadFile(String actionUrl, String[] uploadFilePaths) {
        String end = "rn";
        String twoHyphens = "--";
        String boundary = "*****";

        DataOutputStream ds = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;

        try {
            // 统一资源
            URL url = new URL(actionUrl);
            // 连接类的父类,抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;

            // 设置是否从httpUrlConnection读入,默认情况下是true;
            httpURLConnection.setDoInput(true);
            // 设置是否向httpUrlConnection输出
            httpURLConnection.setDoOutput(true);
            // Post 请求不能使用缓存
            httpURLConnection.setUseCaches(false);
            // 设定请求的方法,默认是GET
            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码连接参数
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 设置请求内容类型
            httpURLConnection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

            // 设置DataOutputStream
            ds = new DataOutputStream(httpURLConnection.getOutputStream());
            for (int i = 0; i < uploadFilePaths.length; i++) {
                String uploadFile = uploadFilePaths[i];
                String filename = uploadFile.substring(uploadFile.lastIndexOf("\") + 1);
                ds.writeBytes(twoHyphens + boundary + end);
                ds.writeBytes("Content-Disposition: form-data; " + "name="file" + i + "";filename="" + filename + """ + end);
                ds.writeBytes(end);
                FileInputStream fStream = new FileInputStream(uploadFile);
                int bufferSize = 1024;
                byte[] buffer = new byte[bufferSize];
                int length = -1;
                while ((length = fStream.read(buffer)) != -1) {
                    ds.write(buffer, 0, length);
                }
                ds.writeBytes(end);
                
                fStream.close();
            }

            ds.writeBytes(twoHyphens + boundary + twoHyphens + end);
            
            ds.flush();
            if (httpURLConnection.getResponseCode() >= 300) {
                throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());
            }

            if (httpURLConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                inputStream = httpURLConnection.getInputStream();
                inputStreamReader = new InputStreamReader(inputStream);
                reader = new BufferedReader(inputStreamReader);
                tempLine = null;
                resultBuffer = new StringBuffer();
                while ((tempLine = reader.readLine()) != null) {
                    resultBuffer.append(tempLine);
                    resultBuffer.append("n");
                }
            }

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (ds != null) {
                try {
                    ds.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (inputStreamReader != null) {
                try {
                    inputStreamReader.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }

            return resultBuffer.toString();
        }
    }

下载文件方法代码:

public static File downloadFile(String urlPath, String downloadDir) {
        File file = null;
        try {
            // 统一资源
            URL url = new URL(urlPath);
            // 连接类的父类,抽象类
            URLConnection urlConnection = url.openConnection();
            // http的连接类
            HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
            // 设定请求的方法,默认是GET
            httpURLConnection.setRequestMethod("POST");
            // 设置字符编码
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            // 打开到此 URL 引用的资源的通信链接(如果尚未建立这样的连接)。
            httpURLConnection.connect();

            // 文件大小
            int fileLength = httpURLConnection.getContentLength();

            // 文件名
            String filePathUrl = httpURLConnection.getURL().getFile();
            String fileFullName = filePathUrl.substring(filePathUrl.lastIndexOf(File.separatorChar) + 1);

            System.out.println("file length---->" + fileLength);

            URLConnection con = url.openConnection();

            BufferedInputStream bin = new BufferedInputStream(httpURLConnection.getInputStream());

            String path = downloadDir + File.separatorChar + fileFullName;
            file = new File(path);
            if (!file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }
            OutputStream out = new FileOutputStream(file);
            int size = 0;
            int len = 0;
            byte[] buf = new byte[1024];
            while ((size = bin.read(buf)) != -1) {
                len += size;
                out.write(buf, 0, size);
                // 打印下载百分比
                System.out.println("下载了-------> " + len * 100 / fileLength + "%n");
            }
            bin.close();
            out.close();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            return file;
        }

    }

编写服务端代码
Controller类,使用MultipartHttpServletRequest 接受多个文件,再使用其getFIleMap()方法获取值为MultipartFile的Map,通过Entry进行遍历获得每一个文件,代码如下:

import com.hk.httpserver.entity.File;
import com.hk.httpserver.service.FileService;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Map;

@RestController
public class FileController {

    @Resource
    FileService fileService;

    @PostMapping("/upload")
    public String upload(MultipartHttpServletRequest req) {
        Map fileMap = req.getFileMap();
        boolean isSuccessed = true;
        try {
            for(Map.Entry entry : fileMap.entrySet()) {
                fileService.saveFile(entry.getValue());
            }
        } catch (IOException e) {
            isSuccessed = false;
        }

        return isSuccessed ? "上传成功" : "上传失败";
    }

    @PostMapping("/download/{fileName}")
    public byte[] download(@PathVariable("fileName") String fileName) {
        File file = fileService.getFile(fileName);
        return file == null ? new byte[]{} : file.getFileContent();
    }

}

Service接口及实现,代码如下:

import com.hk.httpserver.entity.File;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

public interface FileService {

    void saveFile(MultipartFile file) throws IOException;

    File getFile(String fileName);
}
import com.hk.httpserver.entity.File;
import com.hk.httpserver.mapper.FileMapper;
import com.hk.httpserver.service.FileService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Date;

@Service
public class FileServiceImpl implements FileService {

    @Resource
    FileMapper fileMapper;

    @Override
    public void saveFile(MultipartFile file) throws IOException {
        File _file = new File();
        String fileName = file.getOriginalFilename();
        _file.setFileName(fileName);
        _file.setFileType(file.getOriginalFilename().substring(fileName.lastIndexOf(".") + 1));
        _file.setFileContent(file.getBytes());
        _file.setUploadTime(new Date());
        fileMapper.insert(_file);

    }

    @Override
    public File getFile(String fileName) {
        return fileMapper.selectByFileName(fileName);
    }
}

使用MyBatis-Plus,Mapper代码如下:

import com.baomidou.mybatisplus.core.mapper.baseMapper;
import com.hk.httpserver.entity.File;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface FileMapper extends baseMapper {

    @Select("SELECT FILE_ID, FILE_NAME, FILE_TYPE, UPLOAD_TIME, FILE_ConTENT FROM FILE WHERe FILE_NAME = #{fileName}")
    File selectByFileName(@Param("fileName") String fileName);

}

实体类File,代码如下:

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Getter;
import lombok.Setter;

import java.util.Date;

@TableName("FILE")
@Getter
@Setter
public class File {
    @TableId(value = "FILE_ID", type = IdType.ASSIGN_UUID)
    private String fileId;
    @TableField("FILE_NAME")
    private String fileName;
    @TableField("FILE_TYPE")
    private String fileType;
    @TableField("UPLOAD_TIME")
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm",timezone="GMT+8")
    private Date uploadTime;
    @TableField("FILE_CONTENT")
    private byte[] fileContent;
}

建表语句也放这里吧!

DROP TABLE IF EXISTS `file`;
CREATE TABLE `file`  (
  `FILE_ID` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '主键',
  `FILE_NAME` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '文件名',
  `FILE_TYPE` varchar(10) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '文件类型,后缀',
  `UPLOAD_TIME` datetime(0) NULL DEFAULT NULL COMMENT '上传的时间',
  `FILE_CONTENT` mediumblob NOT NULL COMMENT '文件内容',
  PRIMARY KEY (`FILE_ID`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

服务端的application.yml文件,驱动有的mysql是com.mysql.cj.jdbc.Driver,自己改一下吧

server:
  port: 8890
  session-timeout: 300
  tomcat.max-threads: 0
  tomcat.uri-encoding: UTF-8

spring:
  datasource:
    url: jdbc:mysql:127.0.0.1:3306/file_db?
    driver-class-name: com.mysql.jdbc.Driver
    username: xxxxxxxx
    password: xxxxxxxx

最后,在客户端测试一下吧

import com.hk.httpclient.http.HttpHelper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
class HttpClientApplicationTests {

    @Test
    void upload() {
		//测试上传
        System.out.println(HttpHelper.uploadFile("http://127.0.0.1:8890/upload", new String[] { "C:\Users\Lenovo\Desktop\git.txt",  "C:\Users\Lenovo\Desktop\sword_2.png"}));
     	//测试下载
//        HttpHelper.downloadFile("http://127.0.0.1:8890/download/git.txt", "C:\Users\Lenovo\Desktop");
    }

}

哇!大成功!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/424451.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号