所以我正在使用django和文件上传,我需要一个javascript函数在文件上传后执行.我在views.py中有一个文件上传处理程序,如下所示:
def upload_file(request):
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
for f in request.FILES.getlist('fileAttachments'):
handle_uploaded_file(f)
return HttpJavascriptResponse('parent.Response_OK();')
else:
return HttpResponse("Failed to upload attachment.")
Run Code Online (Sandbox Code Playgroud)
我从http://djangosnippets.org/snippets/341/找到了一个django片段,并将HttpJavascriptResponse类放在我的views.py代码中.它看起来如下:
class HttpJavascriptResponse(HttpResponse):
def __init__(self,content):
HttpResponse.__init__(self,content,mimetype="text/javascript")
Run Code Online (Sandbox Code Playgroud)
但是,当我上传文件时,浏览器简单呈现"parent.Response_OK();" 在屏幕上,而不是实际执行JavaScript.Chrome会向我发出警告:"资源被解释为文档,但使用MIME类型text/javascript传输"
反正有没有得到views.py来执行脚本?
我看了看这个问题.我正在寻找一种方法来做那个问题的OP也想要的,那就是在发送http响应之后继续处理php,但是在Symfony2中.
我实现了一个在每次内核终止后触发的事件.到目前为止一切都那么好,但我想要的是它在CERTAIN终止后,在特定的控制器动作中触发,例如在发送表单之后,而不是每次请求时.这是因为我想在某些时候做一些繁重的任务,并且不希望最终用户等待页面加载.
知道我该怎么办?
<?php
namespace MedAppBundle\Event;
use JMS\DiExtraBundle\Annotation\InjectParams;
use JMS\DiExtraBundle\Annotation\Service;
use JMS\DiExtraBundle\Annotation\Tag;
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Console\ConsoleEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use JMS\DiExtraBundle\Annotation\Inject;
/**
* Class MedicListener
* @package MedAppBundle\EventListener
* @Service("medapp_test.listener")
* @Tag(name="kernel.event_subscriber")
*/
class TestListener implements EventSubscriberInterface
{
private $container;
private $logger;
/**
* Constructor.
*
* @param ContainerInterface $container A ContainerInterface instance
* @param LoggerInterface $logger A LoggerInterface instance
* @InjectParams({
* "container" = @Inject("service_container"),
* "logger" = @Inject("logger")
* })
*/ …Run Code Online (Sandbox Code Playgroud) 我发布了一个请求,我想收到一个'成功'字符串作为响应.我收到一个HttpResponseError,下面的图片中显示了以下信息.
PurchaseOrderService
postPurchaseOrderCustom(purchaseOrderCustom: PurchaseOrderSaveCustom) {
const url = `${this.localUrl}purchaseOrderCustom`;
return this.http.post<String>(url, purchaseOrderCustom, {headers: this.header})
.pipe(
catchError(this.handleError('postPurchaseOrderCustom', 'I am an error'))
);
}
Run Code Online (Sandbox Code Playgroud)
PurchaseOrderComponent
this.purchaseOrderService.postPurchaseOrderCustom(purchaseOrderCustom).subscribe( response => {
console.log("Testing", response);
},
error => {
console.error('errorMsg',error );
}
Run Code Online (Sandbox Code Playgroud)
我这样做的方式与文档中的完成方式相同.请指出我做错了什么.
正如其他几篇文章中所述(请参阅下面的参考资料)我试图创建响应过滤器,以便修改由另一个Web应用程序生成的内容.
我将基本的字符串转换逻辑工作并封装到源自公共FilterBase的Filters中.但是,逻辑必须对完整内容进行操作,而不是对内容进行操作.因此,我需要在写入时缓存块,并在完成所有写入时执行过滤器.
如下所示,我创建了一个从MemoryStream派生的新ResponseFilter.在写入时,内容缓存到另一个MemoryStream.在Flush上,现在在MemoryStream中的完整内容将转换为字符串,并且Filter逻辑将启动.然后将修改后的内容写回原始流.
但是,在每个第二个请求(基本上当一个新的过滤器在前一个过滤器上实例化)时,正在执行前一个过滤器的Flush方法.此时,由于_cachedStream为空,应用程序在_outputStream.Write()方法上崩溃.
活动顺序如下:
我有几个问题:
注意:如果我不重写Close方法,我会遇到完全相同的行为(减去Close事件).
public class ResponseFilter : MemoryStream
{
private readonly Stream _outputStream;
private MemoryStream _cachedStream = new MemoryStream(1024);
private readonly FilterBase _filter;
public ResponseFilter (Stream outputStream, FilterBase filter)
{
_outputStream = outputStream;
_filter = filter;
}
// Flush is called on the second, fourth, and so on, page request (second request) with empty content.
public override void Flush() …Run Code Online (Sandbox Code Playgroud) 我有一个Java webapp创建一个pdf并将其流回浏览器.
byte[] pdf = report.exportPdfToArray(user);
response.setContentType("application/pdf");
response.setHeader("content-disposition", "inline; filename=\"My.pdf\"");
outStream = response.getOutputStream();
outStream.write(pdf);
outStream.flush();
outStream.close();
Run Code Online (Sandbox Code Playgroud)
报告被执行并被发送回浏览器,但即使我设置了,我也无法控制文件的名称content-disposition.我正在使用Jboss 4.2.1.你知道我错过了什么吗?
编辑:当内容处置是内联时,有没有办法设置文件名?
我正在尝试HttpResponseException按照此截屏视频中的描述进行提升(约1分钟)
throw new HttpResponseException(HttpStatusCode.Unauthorized);
Run Code Online (Sandbox Code Playgroud)
但该应用程序将无法编译,因为它会引发以下错误:
The best overloaded method match for 'System.Web.Http.HttpResponseException.HttpResponseException(System.Net.Http.HttpResponseMessage)' has some invalid arguments
Run Code Online (Sandbox Code Playgroud)
msdn上的文档说它有一个接受HttpResponseMessage枚举的构造函数.http://msdn.microsoft.com/en-us/library/hh835324%28v=vs.108%29.aspx
我错过了什么?
谢谢
我有一个网页,当我访问材料时返回以下标题:
HTTP/1.1 200 OK
Date: Sat, 29 Jun 2013 15:57:25 GMT
Server: Apache
Content-Length: 2247515
Cache-Control: no-cache, no-store, must-revalidate, max-age=-1
Pragma: no-cache, no-store
Expires: -1
Connection: close
Run Code Online (Sandbox Code Playgroud)
使用chrome扩展,我想修改它,response header以便实际缓存材料而不是浪费带宽.
我有以下示例代码:
chrome.webRequest.onHeadersReceived.addListener(function(details)
{
// Delete the required elements
removeHeader(details.responseHeaders, 'pragma');
removeHeader(details.responseHeaders, 'expires');
// Modify cache-control
updateHeader(details.responseHeaders, 'cache-control', 'max-age=3600;')
console.log(details.url);
console.log(details.responseHeaders);
return{responseHeaders: details.responseHeaders};
},
{urls: ["<all_urls>"]}, ['blocking', 'responseHeaders']
);
Run Code Online (Sandbox Code Playgroud)
这正确地将标题修改为这样的东西(基于console.log()输出):
HTTP/1.1 200 OK
Date: Sat, 29 Jun 2013 15:57:25 GMT
Server: Apache
Content-Length: 2247515
Cache-Control: max-age=3600
Connection: close
Run Code Online (Sandbox Code Playgroud)
但基于我试图检查的所有内容,我无法看到任何证据确实发生了这种情况:
google-chrome httpresponse cache-control http-headers google-chrome-extension
我总是statusCode=200在客户端获得ajax帖子,而服务器则回答HttpStatusCode.Unauthorized.
我的控制器代码:
public class AccountApiController : ApiController
{
public HttpResponseMessage Login(HttpRequestMessage request, [FromBody]LoginViewModel loginModel)
{
return request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Unauthorized login.");
}
}
Run Code Online (Sandbox Code Playgroud)
我的ajax代码:
$.ajax({
url: '/api/accountapi/login',
type: 'POST',
data: data
})
.done(function (object, status, xhr) {
alert("Success: " + xhr.status + " : " + xhr.statusText);
})
.always(function (object) {
$("#output").text(JSON.stringify(object, null, 4));
});
Run Code Online (Sandbox Code Playgroud)
结果:带文本Success: 200 : OK
和输出窗口的警报:
{
"Message": "Unauthorized login."
}
Run Code Online (Sandbox Code Playgroud)
所以,我可以得到文本错误消息,但我需要让HttpStatusCode来处理错误语句.请帮帮我.
有关此问题的更多信息以及来自Brock Allen的优雅解决方案:http: //brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/
在Node with Express中,我有一段这样的代码.
if (req.body.var1 >= req.body.var2){
res.json({success: false, message: "End time must be AFTER start time"});
console.log('Hi')
}
console.log('Hi2')
//other codes
Run Code Online (Sandbox Code Playgroud)
我预计如果var1> = var2,将发送响应并执行结束.像Java/C#中的return语句
但显然情况并非如此.发送响应后,"Hi"和"Hi2"以及之后的所有其他代码继续执行.
我想知道如何阻止这种情况发生?
此外,我想知道在什么情况下你真的希望代码在响应已经发送后继续执行.
干杯
我的问题是,当父资源或更高资源不存在/已被删除时,我是否应该返回HTTP响应代码400 Bad Request,404 Not Found或410 Gone?
寻找一些有关如何处理RESTful资源树中缺失链接的指导,因为我已经阅读了很多但没有很多个人经验。
假设我们具有以下资源结构:
/users/{userId}/accounts/{accoundId}/logs/{logId}
Run Code Online (Sandbox Code Playgroud)
一个用户可以拥有多个帐户,而这些帐户又可以具有许多订单,而这些订单又可以具有许多日志。日志仅针对单个帐户存在,而帐户仅针对单个用户存在。没有帐户就不能存在日志,没有用户就不能存在帐户。
当我尝试解决以下问题时,我的问题来了:
/users/123/accounts/321/logs - POST
/users/123/accounts/321/logs/987 - GET
/users/123/accounts/321/logs/987 - PUT
/users/123/accounts/321/logs/987 - DELETE
/users/123/accounts/321/logs/987 - PATCH
/users/123/accounts/321/logs/987 - HEAD
Run Code Online (Sandbox Code Playgroud)
但是此资源不存在或不再存在:
/users/123/accounts/321
Run Code Online (Sandbox Code Playgroud)
或此资源不存在或不再存在:
/users/123
Run Code Online (Sandbox Code Playgroud)
我可以说这是一个400 Bad Request,根据RFC7231:
6.5.1。400错误的要求
400(错误请求)状态代码表示服务器由于某些原因(例如格式错误的请求语法,无效的请求消息框架或欺骗性的请求路由)而被视为客户端错误,因此服务器无法或不会处理该请求。
从定义上讲是正确的,除非高速缓存尚未过期,这意味着应用程序尚未重新遍历层次结构,而另一个应用程序已删除了父资源。通过提供相关的oplock,客户端将证明,根据其最新知识,它正在发出语义上正确的请求。
我本能地会向“ 404 Not Found”或“ 410 Gone”借钱,即使这不是缓存内容,因为失败的原因实际上是缺少/不可用的资源。但是,按照RFC7231规范:
6.5.4。找不到404
404(未找到)状态代码表示原始服务器未找到目标资源的当前表示,或不愿意透露该资源的存在。404状态代码不表示这种缺乏表示是暂时的还是
永久的;如果
原始服务器大概通过某种可配置的方式得知该条件很可能是永久性的,则与404相比,首选410(已消失)状态代码。
要么
6.5.9。410去了
410(已消失)状态代码指示在源服务器上不再可以访问目标
资源,并且这种
情况很可能是永久的。
这些似乎在欺骗本能。
是否有人在处理这种或类似场景和良好方法方面有任何经验?我觉得应该使用正确的感觉,以及使用此服务时应该看到的东西,而不是文字文字。
httpresponse ×10
c# ×3
http ×2
rest ×2
ajax ×1
angular ×1
asp.net ×1
django ×1
django-views ×1
express ×1
filter ×1
flush ×1
http-headers ×1
iostream ×1
java ×1
javascript ×1
jquery ×1
json ×1
node.js ×1
pdf ×1
php ×1
servlets ×1
stream ×1
symfony ×1
typescript ×1