Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

spring boot上传文件时数据流二次读取如何解决啊?

如果没有文件上传,可以写一个包装器

package dry.framework.service;
import dry.base.service.StreamService;
import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class RequestWrapperService extends HttpServletRequestWrapper {
    private String body;
 public RequestWrapperService(HttpServletRequest request) {
        super(request);
 try {
            body = new String(StreamService.readStream(request.getInputStream()));
 } catch (IOException e) {
            e.printStackTrace();
 }
    }
    public String getBody() {
        return this.body;
 }
    @Override
 public ServletInputStream getInputStream() {
        final ByteArrayInputStream is = new ByteArrayInputStream(body.getBytes());
 return new ServletInputStream() {
            @Override
 public boolean isFinished() {
                return false;
 }
            @Override
 public boolean isReady() {
                return false;
 }
            @Override
 public void setReadListener(ReadListener readListener) {
            }
            @Override
 public int read() {
                return is.read();
 }
        };
 }
    @Override
 public BufferedReader getReader() {
        return new BufferedReader(new InputStreamReader(this.getInputStream()));
 }
}

然后在过滤器里面这样返回改写的请求对象

chain.doFilter(new RequestWrapperService(r), response);

如果有文件上传,把文件流存成字符串不合适吧,该怎么写呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

对于json类型的请求 如果你只是要拿到body,进行业务操作的话
可以使用requestbodyadvice
image.png
他提供了解析前和解析后的方法


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...