我使用ExtJS为我的程序构建客户端.有一种情况我想向服务器发送Ajax请求,并获取响应文件(二进制文件,而不是纯文本文件,即XLS或PDF).如何通过ExtJS获取返回的文件(我的意思是该文件可以下载并存储到客户端)?我不能var result = Ext.decode(response.responseText)用来接收结果,因为响应包含二进制数据并且无法解码.
Ajax调用非常简单:
Ext.Ajax.request({
url : 'myController/exportFile',
method : 'GET',
success : function(response, opts) {
// What should I do to get the file?
},
failure : function(response, opts) {
alert('Export file failed!')
}
});
Run Code Online (Sandbox Code Playgroud)
这是我的服务器操作返回文件:
public void sendFile(HttpServletResponse response, String filePath) {
def file = new File(filePath);
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=${file.getName()}");
response.outputStream << file.newInputStream();
}
Run Code Online (Sandbox Code Playgroud)
非常感谢!
我在我的项目中使用nanohttpd服务器。请求GET应发送 JSON 文件作为响应,但nanohttpd仅允许String. 我怎样才能做到这一点?
这是 GET 方法:
class GetHandler{
JSONObject response;
JSONObject doGet(Queue queue){
Map.Entry<String, Message> entry = (Map.Entry<String, Message>)queue.getQueue().entrySet().iterator().next();
String key = entry.getKey();
String value = entry.getValue().getText();
int reCount = entry.getValue().increaseCount();
queue.getQueue().remove(key);
Date date = new Date();
long time = date.getTime();
queue.getInFlightQueue().put(key,new Message(value, reCount, time));
System.out.println("ID : " + key + " Message Body : " + value);
response.put("ID",key);
response.put("Message Body", value);
return response;
}
}
Run Code Online (Sandbox Code Playgroud)
这是处理部分:
if (uriComponents[1].equals("queue") && mainHashMap.containsKey(uriComponents[2])) …Run Code Online (Sandbox Code Playgroud) 我在 S3 上有一个 .zip 文件列表,它是动态创建的并传递到 Flask view /download。我的问题似乎不在于循环访问此列表,而在于返回响应,以便将列表中的所有文件下载到用户计算机。如果我有一个视图返回响应,它只会下载第一个文件,因为返回会关闭连接。我尝试了很多方法并研究了类似的问题(例如:Boto3 to download all files from a S3 Bucket),但到目前为止还没有解决这个问题。我还研究了流媒体(如这里: http: //flask.pocoo.org/docs/1.0/patterns/streaming/)并尝试创建一个作为生成器的子函数,但同样的问题仍然存在,因为我仍然必须将返回值传递给 View 函数 - 这是最后一个代码示例:
@app.route('/download', methods=['POST'])
def download():
download=[]
download = request.form.getlist('checked')
def generate(result):
s3_resource = boto3.resource('s3')
my_bucket = s3_resource.Bucket(S3_BUCKET)
d_object = my_bucket.Object(result).get()
yield d_object['Body'].read()
for filename in download:
return Response (generate(filename), mimetype='application/zip', headers={'Content-Disposition': 'attachment;filename=' + filename})
Run Code Online (Sandbox Code Playgroud)
为了下载所有文件,最好的方法是什么?有没有更简单的方法将列表传递给 boto3 或任何其他 Flask 模块来下载这些文件?
我有这段代码可以从 URL 获取页面 HTML,但是响应内容看起来是经过编码的。
代码:
HttpWebRequest xhr = (HttpWebRequest) WebRequest.Create(new Uri("https://www.youtube.com/watch?v=_Ewh75YGIGQ"));
xhr.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
//xhr.CookieContainer = request.Account.CookieContainer;
xhr.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";
xhr.Headers["Accept-Encoding"] = "gzip, deflate, br";
xhr.Headers["Accept-Language"] = "en-US,en;q=0.5";
xhr.Headers["Upgrade-Insecure-Requests"] = "1";
xhr.KeepAlive = true;
xhr.UserAgent = "Mozilla/4.0 (compatible; MSIE 9.0; Windows NT 6.1)";
xhr.Host = "www.youtube.com";
xhr.Referer = "https://www.youtube.com/watch?v=6aCpYxzRkf4";
var response = xhr.GetResponse();
string html;
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
html = reader.ReadToEnd();
}
Run Code Online (Sandbox Code Playgroud)
这些是响应标头:
X-XSS-Protection: 1; mode=block; report=https://www.google.com/appserve/security-bugs/log/youtube
X-Content-Type-Options: nosniff
X-Frame-Options: SAMEORIGIN
Strict-Transport-Security: max-age=31536000
Content-Encoding: …Run Code Online (Sandbox Code Playgroud) 我是一个相当新的 graphQL。我的要求是发送查询时,graphQL 应返回 JSON 响应,如下所示
{
user: '$',
name: 'Josh',
age: '30'
}
Run Code Online (Sandbox Code Playgroud)
我尝试了以下方法,但没有达到结果。
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
var schema = buildSchema(`
type Query {
user: String!
}
`);
// JSON
var json = {
user: '$',
name: 'Josh',
age: '30'
};
var root = {
user: () => {
return json;
}
};
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000);
console.log('Running a …Run Code Online (Sandbox Code Playgroud) 我一直在尝试使用 Typegoose 使用类转换器库来完成 Mongodb 序列化部分的 NestJs 示例。https://docs.nestjs.com/techniques/serialization中给出的示例仅展示了如何在 TypeORM 中使用序列化。我对 Typegoose 遵循了相同的流程。这是我到目前为止所尝试过的。
// cat.domain.ts
import { prop } from '@typegoose/typegoose';
export class Cat {
@prop()
name: string;
@prop()
age: number;
@prop()
breed: string;
}
// cats.service.ts
@Injectable()
export class CatsService {
constructor(
@InjectModel(Cat) private readonly catModel: ReturnModelType<typeof Cat>,
) {}
findAll(): Observable<Cat[]> {
return from(this.catModel.find().exec());
}
findOne(id: string): Observable<Cat> {
return from(this.catModel.findById(id).exec());
}
...
}
// cat.response.ts
import { ObjectId } from 'mongodb';
import { Exclude, Transform } from …Run Code Online (Sandbox Code Playgroud) 如果出现未处理的错误,SpringBoot 应用程序的默认服务器响应是
{
"timestamp": 1594232435849,
"path": "/my/path",
"status": 500,
"error": "Internal Server Error",
"message": "this request is failed because of ...",
"requestId": "ba5058f3-4"
}
Run Code Online (Sandbox Code Playgroud)
我想在应用程序路由的 Springdoc 注释中描述它。
假设有一个标准类DefaultErrorResponse(只是一个模拟名称),它可能如下所示:
@Operation(
// ... other details
responses = {
// ... other possible responses
@ApiResponse(
responseCode = "500",
content = @Content(schema = @Schema(implementation = DefaultErrorResponse.class)))
}
)
Run Code Online (Sandbox Code Playgroud)
在更糟糕的情况下,这样的类不存在,Spring 仅使用Map底层来创建响应。那么这个注释将更加详细,包括明确提及响应中包含的每个字段。
显然,对于大多数路线来说,这部分@ApiResponse(responseCode="500",...是相同的,并且最好减少重复。
在文档中引入默认错误响应描述的正确方法是什么?
我尝试使用 ts-jest 模拟获取响应,但遇到打字稿错误
import { mocked } from 'ts-jest/utils';
import fetch from 'node-fetch';
import { getInstallationAccessToken } from './index';
const mockedFetch = mocked(fetch, true);
describe('getInstallationAccessToken', () => {
const TODAY = new Date();
const TOMORROW = new Date();
TOMORROW.setDate(TODAY.getDate() + 1);
beforeEach(() => {
mockedFetch.mockResolvedValue({
status: 200,
json: async () => ({
token: 'MOCKED_GITHUB_INSTALLATION_ACCESS_TOKEN',
expires_at: TOMORROW.toISOString()
})
});
jest.clearAllMocks();
});
test('generates github app jwt token', async () => {
await getInstallationAccessToken();
expect(mockedJwt.sign).toBeCalledTimes(1);
});
})
Run Code Online (Sandbox Code Playgroud)
在此示例中,我收到以下错误:
Argument of type '{ status: …Run Code Online (Sandbox Code Playgroud) Spring 5 引入了 ResponseStatusException,这让我陷入了困境,不知道在什么情况下可以使用 ResponseStatusException 和 ControllerAdvice,因为它们非常相似。
谁能帮我这个?
error-handling exception response httpresponse controller-advice
使用此函数可以展平从版本 4 上的 Strapi 返回的响应。帮助您摆脱数据和属性属性
这将为您提供与 Strapi 版本 3 相同的响应结构。这将帮助您轻松从版本 3 迁移到版本 4。
如何使用它?
注意:此处的数据是从 Strapi 版本 4 返回的响应。
export const flattenObj = (data) => {
const isObject = (data) =>
Object.prototype.toString.call(data) === "[object Object]";
const isArray = (data) =>
Object.prototype.toString.call(data) === "[object Array]";
const flatten = (data) => {
if (!data.attributes) return data;
return {
id: data.id,
...data.attributes,
};
};
if (isArray(data)) {
return data.map((item) => flattenObj(item));
}
if (isObject(data)) {
if (isArray(data.data)) { …Run Code Online (Sandbox Code Playgroud)