java服务端解析formdata格式文件上传



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.util.Arrays;
import java.util.HashMap;

/**http formData 解析
 * auth: WenYF
 * date: 2018/7/11
 */
public class FormDataAnalysisUtil {
    public static final Logger Log = LoggerFactory.getLogger(FormDataAnalysisUtil.class);

    // 原数据
    private byte[] rawData;
    private int index;
    // 参数
    private HashMap<String, String> params;
    private byte[] fileData;
    private String wrapperName;
    private String contentType;
    private int endSize;
    public FormDataAnalysisUtil(byte[] data) throws IllegalArgumentException {
        rawData = data;
        params = new HashMap<>();
        index = 0;
        parserData();
    }
    
    private void parserData() throws IllegalArgumentException {
        wrapperName = readLine();
        String params = readLine();
        parserParams(params);
        contentType = readLine().split(": ")[1];
        eatRedundantLine();
        // 读取数据
        fileData = Arrays.copyOfRange(rawData, index
                , rawData.length - wrapperName.length() - 2 - endSize - endSize);
    }
        
    private void parserParams(String params) {
        String[] splits = params.split("; ");
        for (int i = 1; i < splits.length; i++) {
            String one = splits[i];
            String[] oneSplits = one.split("=");
            this.params.put(oneSplits[0], oneSplits[1].substring(1, oneSplits[1].length()-1));
        }
    }
    
    public HashMap<String, String> getParams() {
        return params;
    }

    public byte[] getFileData() {
        return fileData;
    }

    public String getWrapperName() {
        return wrapperName;
    }

    public String getContentType() {
        return contentType;
    }
    
    private String readLine() {
        boolean done = false;
        int startIndex = index;
        int count = 0;
        while (!done) {
            if (isLineEnd()) {
                done = true;
            } else {
                index++;
                count++;
            }
        }
        
        try {
            // TODO 编码自行协商,默认UTF-8
            return new String(rawData, startIndex, count, "utf-8");
        } 
        catch (UnsupportedEncodingException e) {
            Log.error(e.getMessage(), e);
            return new String(rawData, startIndex, count);
        }
    }

    private boolean isLineEnd() {
        if (rawData[index] == '\r' && rawData[index+1] == '\n') {
            index+=2;
            endSize = 2;
            return true;
        } else if (rawData[index] == '\n') {
            index++;
            endSize = 1;
            return true;
        } else if (rawData[index] == '\r') {
            index++;
            endSize = 1;
            return true;
        } else {
            return false;
        }
    }

    private void eatRedundantLine() {
        while(isLineEnd()) {};
    }
}

在Servlet中先获取bytes

    public static byte[] getBytes(HttpServletRequest request) throws IOException {
        InputStream is = request.getInputStream();
        int size = -1;

        ByteArrayOutputStream bis = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        while ((size = is.read(buffer)) != -1) {
            bis.write(buffer, 0, size);
        }
        buffer = bis.toByteArray();
        bis.close();

        return buffer;
    }

然后解析bytes

        //获取文件对象
        FormDataAnalysisUtil formData = new FormDataAnalysisUtil(FileUploadUtil.getBytes(req));

获取文件名

String name = formData.getParams().get("filename");

获取文件数据

formData.getFileData()

获取文件类型

String contentType = formData.getContentType();

觉得好用就点个赞。

  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值