5.API中的文件上传与接收

0.需求

通过Java代码完成带有文件的http请求,并且服务端能接收(基于SSM)

1.SpringMVC配置文件

注释掉文件解析器,否则会引起冲突
(代码待优化)

<!-- 上传文件的解析器 -->
    <!-- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        设置上传文件的最大内存
        <property name="maxUploadSize" value="10240000"></property>
    </bean> -->

2.客户端

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;

public class HttpPostUtil {
    URL url;
    HttpURLConnection conn;
    String boundary = "--------httppost123";
    Map<String, String> textParams = new HashMap<String, String>();
    Map<String, File> fileparams = new HashMap<String, File>();
    DataOutputStream ds;

    public HttpPostUtil(String url) throws Exception {
        this.url = new URL(url);
    }

    // 重新设置要请求的服务器地址,即上传文件的地址。
    public void setUrl(String url) throws Exception {
        this.url = new URL(url);
    }

    // 增加一个普通字符串数据到form表单数据中
    public void addTextParameter(String name, String value) {
        textParams.put(name, value);
    }

    // 增加一个文件到form表单数据中
    public void addFileParameter(String name, File value) {
        fileparams.put(name, value);
    }

    // 清空所有已添加的form表单数据
    public void clearAllParameters() {
        textParams.clear();
        fileparams.clear();
    }

    // 发送数据到服务器,返回一个字节包含服务器的返回结果的数组
    public byte[] send() throws Exception {
        initConnection();
        try {
            conn.connect();
        } catch (SocketTimeoutException e) {
            // something
            throw new RuntimeException();
        }
        ds = new DataOutputStream(conn.getOutputStream());
        writeFileParams();
        writeStringParams();
        paramsEnd();
        InputStream in = conn.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int b;
        while ((b = in.read()) != -1) {
            out.write(b);
        }
        conn.disconnect();
        return out.toByteArray();
    }

    // 文件上传的connection的一些必须设置
    private void initConnection() throws Exception {
        conn = (HttpURLConnection) this.url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setConnectTimeout(10000); // 连接超时为10秒
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        conn.setRequestProperty("connection", "Keep-Alive");
        conn.setRequestProperty("Charsert", "UTF-8");
        conn.setRequestProperty("Accept-Charset", "UTF-8");
    }

    // 普通字符串数据
    private void writeStringParams() throws Exception {
        Set<String> keySet = textParams.keySet();
        for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
            String name = it.next();
            String value = textParams.get(name);
            ds.writeBytes("--" + boundary + "\r\n");
            ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"\r\n");
            ds.writeBytes("\r\n");
            ds.writeBytes(encode(value) + "\r\n");
        }
    }

    // 文件数据
    private void writeFileParams() throws Exception {
        Set<String> keySet = fileparams.keySet();
        for (Iterator<String> it = keySet.iterator(); it.hasNext();) {
            String name = it.next();
            File value = fileparams.get(name);
            ds.writeBytes("--" + boundary + "\r\n");
            ds.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"; filename=\"" + encode(value.getName())
                    + "\"\r\n");
            ds.writeBytes("Content-Type: " + getContentType(value) + "\r\n");
            ds.writeBytes("\r\n");
            ds.write(getBytes(value));
            ds.writeBytes("\r\n");
        }
    }

    // 获取文件的上传类型,图片格式为image/png,image/jpg等。非图片为application/octet-stream
    private String getContentType(File f) throws Exception {

        // return "application/octet-stream"; //
        // 此行不再细分是否为图片,全部作为application/octet-stream 类型
        ImageInputStream imagein = ImageIO.createImageInputStream(f);
        if (imagein == null) {
            return "application/octet-stream";
        }
        Iterator<ImageReader> it = ImageIO.getImageReaders(imagein);
        if (!it.hasNext()) {
            imagein.close();
            return "application/octet-stream";
        }
        imagein.close();
        return "image/" + it.next().getFormatName().toLowerCase();// 将FormatName返回的值转换成小写,默认为大写

    }

    // 把文件转换成字节数组
    private byte[] getBytes(File f) throws Exception {
        FileInputStream in = new FileInputStream(f);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int n;
        while ((n = in.read(b)) != -1) {
            out.write(b, 0, n);
        }
        in.close();
        return out.toByteArray();
    }

    // 添加结尾数据
    private void paramsEnd() throws Exception {
        ds.writeBytes("--" + boundary + "--" + "\r\n");
        ds.writeBytes("\r\n");
    }

    // 对包含中文的字符串进行转码,此为UTF-8。服务器那边要进行一次解码
    private String encode(String value) throws Exception {
        return URLEncoder.encode(value, "UTF-8");
    }

    public static void main(String[] args) throws Exception {
        HttpPostUtil u = new HttpPostUtil("http://127.0.0.1:8080/SaveCoreData/receiveData");
        u.addFileParameter("testTXT", new File("C:\\Users\\dell\\Desktop\\hello.txt"));
        u.addTextParameter("text", "中文");
        byte[] b = u.send();
        String result = new String(b);
        System.out.println(result);

    }

}

3.服务端

@RequestMapping(value = "/receiveData")
public void receiveData(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String tempPath = request.getServletContext().getRealPath("/temp");
    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(1024*1024*1024);//设置缓存大小
    factory.setRepository(new File(tempPath));//默认情况下 临时文件不会自动删除
    ServletFileUpload upload = new ServletFileUpload(factory);
    List<FileItem> parseRequest = upload.parseRequest(request);

    for (FileItem item : parseRequest) {
        boolean formField = item.isFormField();
        if (formField) {
            String fieldName = item.getFieldName();
            String value = item.getString();
            value = new String(value.getBytes("iso-8859-1"), "utf-8");
            System.out.println(fieldName+"----"+value);
        } else {
            item.delete();
            String fileName = item.getName();
            fileName = FileUploadUtils.getRealName(fileName);
            String randomDir = FileUploadUtils.getRandomDir(fileName);
            String dirPath = null;
            //客服上传的附件
            dirPath = "/var/upload/servicer" + randomDir;
            File file = new File(dirPath);
            if (!file.exists()) {
                file.mkdirs();
            }

            InputStream in = item.getInputStream();
            OutputStream out = new FileOutputStream(dirPath + "/" + fileName);
            //拷贝的代码
            IOUtils.copy(in, out);
            in.close();
            out.close();
            //item删除临时文件的方法
        }
    }

}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 您好,我可以回答这个问题。使用 FastAPI 接收 Excel 文件的方法如下: 1. 安装依赖库:pandas 和 fastapi 2. 在 FastAPI 定义一个路由,用于接收文件上传请求: ```python from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/uploadfile/") async def create_upload_file(file: UploadFile = File(...)): return {"filename": file.filename} ``` 3. 在路由使用 UploadFile 类型的参数来接收上传文件,然后返回文件名或其他信息。 4. 在客户端发送文件上传请求时,需要使用 multipart/form-data 格式,并将文件作为表单数据的一部分上传。 希望这个回答能够帮到您。 ### 回答2: FastAPI是一个基于Python的快速、现代化的 Web 框架,可以用于构建高性能的 API。要实现 FastAPI 接收 Excel 文件,可以借助一些库和方法来处理。 首先,在 FastAPI 的主文件,需要导入相关的库和模块,如`fastapi`、`fastapi.UploadFile`和`openpyxl`等。这些库可以用于处理 HTTP 请求和解析 Excel 文件。 然后,需要定义一个 POST 路由,用于接收上传的 Excel 文件。可以通过`fastapi.UploadFile`类型的参数来定义接收文件,然后读取该文件并解析 Excel 数据。 接下来,使用`openpyxl`库来打开 Excel 文件,并获取其的数据。可以通过定义一个函数或方法来实现这个解析的逻辑。在这个函数,可以使用`openpyxl`提供的方法来遍历 Excel 文件的单元格,并读取其数据。 最后,在定义的 POST 路由,调用这个解析 Excel 文件的函数,将其结果返回给客户端。可以将解析出的数据以 JSON 格式返回,方便客户端进行后续的处理。 需要注意的是,为了保证代码的可靠性和安全性,可以对上传的 Excel 文件进行一些校验和限制。例如,可以检查上传文件的类型是否为 Excel 文件文件大小是否符合要求,以及对解析过程的异常情况进行处理和错误提示。 以上是一个大致的思路,你可以根据自己的需求和具体实现来进行调整。希望这些信息能对你有所帮助! ### 回答3: FastAPI是一个高性能的Web框架,可以用来构建API接收Excel文件的方法主要有两种:通过表单上传和通过API请求。 通过表单上传Excel文件,可以使用FastAPI的`Form`参数。首先,需要安装`python-multipart`库,然后在路由使用`File`和`Form`参数接收文件,并使用`upload_file`方法保存文件。示例代码如下: ```python from fastapi import FastAPI, File, Form app = FastAPI() @app.post("/upload") async def upload_file(file: bytes = File(...), excel_file: UploadFile = File(...), name: str = Form(...)): # 在此处进行Excel文件的处理 return {"filename": excel_file.filename, "name": name} ``` 通过API请求发送Excel文件,可以使用FastAPI的`UploadFile`参数。在路由使用`File`参数接收文件,并使用`upload_file`方法保存文件。示例代码如下: ```python from fastapi import FastAPI, File, UploadFile app = FastAPI() @app.post("/upload") async def upload_file(file: bytes = File(...), excel_file: UploadFile = File(...)): # 在此处进行Excel文件的处理 return {"filename": excel_file.filename} ``` 以上是两种通过FastAPI接收Excel文件的方法。具体的处理逻辑可以根据实际需求进行编写。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值