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);
如果有文件上传,把文件流存成字符串不合适吧,该怎么写呢?
回答
对于json类型的请求 如果你只是要拿到body,进行业务操作的话
可以使用requestbodyadvice
他提供了解析前和解析后的方法
以上是 spring boot上传文件时数据流二次读取如何解决啊? 的全部内容, 来源链接: utcz.com/a/72274.html