Servlet-文件上传

1。文件结构

这是一个普通的原生的Java Web项目
在这里插入图片描述

2。代码

StreamUtil.java
package com.imut.action;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author djs
 * @create 2022-11-25 23:20
 */
public class StreamUtil {

    private StreamUtil(){}

    /**
     * 将InputStream输入流转为byte字节流
     * 适用于发送文件
     * @param is
     * @return
     * @throws Exception
     */
    public static byte[] streamToByArray(InputStream is) throws Exception {
        // 创建输出流对象
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] b = new byte[1024];
        int len;
        while ((len = is.read(b)) != -1){
            bos.write(b,0,len);
        }
        byte[] bytes = bos.toByteArray();
        bos.close();
        return bytes;
    }


    /**
     * 将InputStream转为String
     * @param is
     * @return
     * @throws Exception
     */
    public static String streamToString(InputStream is) throws Exception {
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line=reader.readLine()) != null){
            builder.append(line+"\r\n");
        }
        return builder.toString();
    }


}

UploadAction.java
package com.imut.action;

import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.annotation.MultipartConfig;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.Part;

import java.io.*;
import java.nio.charset.StandardCharsets;

/**
 * @author djs
 * @create 2022-11-26 22:22
 */
@WebServlet("/upload")
@MultipartConfig
public class UploadAction extends HttpServlet {

    // 设置保存的位置
    private static final String savePath = "F://test//";

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {

        request.setCharacterEncoding("UTF-8");
        // 上传的结果
        String upload = upload(request);
        System.out.println("upload = " + upload);

    }



    public static String upload(HttpServletRequest request) {

        String fileName = "";

        try {
            Part pohto = request.getPart("file");
            // 上传的文件名称
            fileName = pohto.getSubmittedFileName();
            // 上传文件的大小
            long size = pohto.getSize();
            System.out.println("size = "+size);
            // 上传文件的文件流
            InputStream inputStream = pohto.getInputStream();
            // 将文件流转为byte数组
            byte[] bytes = StreamUtil.streamToByArray(inputStream);
            // 创建一个缓冲输出流 保存上传的文件
            BufferedOutputStream bufferedOutputStream =
                    new BufferedOutputStream(new FileOutputStream(savePath+fileName));

            bufferedOutputStream.write(bytes);
            // 刷新
            bufferedOutputStream.flush();
            // 关闭流
            bufferedOutputStream.close();

            pohto.write(fileName);

            return "上传成功";
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ServletException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "上传失败";
    }


}

index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>文件上传</title>
</head>
<body>

<h2>文件上传</h2>
<form action="upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file">
    <input type="submit" value="上传">
</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值