我们都知道我们可以通过在.htaccess文件中添加以下行来为图像指定缓存验证器:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresDefault "access plus 1 year"
</IfModule>
Run Code Online (Sandbox Code Playgroud)
..和..
<IfModule mod_headers.c>
<FilesMatch "\.(bmp|css|flv|gif|ico|jpg|jpeg|js|pdf|png|svg|swf|tif|tiff)$">
Header set Last-Modified "Mon, 31 Aug 2009 00:00:00 GMT"
</FilesMatch>
</IfModule>
Run Code Online (Sandbox Code Playgroud)
但是,它对真正的JPG或PNG文件有效.但问题是,如何为使用PHP代码和imagejpeg/imagepng函数构建的图像指定缓存验证器?(以上代码对他们无效)
PS:我试图使用.htaccess文件模拟PHP创建的图像的URL,如真实图像(例如:http://example.com/1.jpg
由PHP文件生成并且不是真正的.jpg图像),但仍然接收缓存验证器警告.
我正在通过带有请求正文的HTTP GET从REST API中检索图像。
我设法通过测试使用node.js
和检查了返回的内容chai.js
:
expect(res).to.have.header('Content-Type', 'image/jpeg');
expect(res).to.have.header('Access-Control-Allow-Origin', '*');
expect(res).to.have.header('Access-Control-Allow-Headers', 'Access-Control-Allow-Headers, Origin, X-Requested-With, Content-Type, Accept, Authorization');
expect(res).to.have.header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD');
expect(res).to.have.status(200);
expect(res.body).to.be.instanceof(Buffer); // the image content
Run Code Online (Sandbox Code Playgroud)
在vue.js
文件中,我习惯将图像附加到<img ...>
HTML标记上,如下所示:
<img v-bind:src="urlImg">
Run Code Online (Sandbox Code Playgroud)
然后在javascript部分中指定如下网址:
# this string representing the URL is returned by a function
this.urlImg = 'http://example.com/my_img.jpeg'
Run Code Online (Sandbox Code Playgroud)
但是在这种情况下,我无法提供URL,因为HTTP GET希望正文返回具有内容类型的图像image/jpeg
。
我什至不确定这是否可行,而且我可能误会了内容类型image/jpeg
应该如何工作。我该怎么做vue.js
?有可能吗?有没有一种方法可以检查此HTTP响应的图像内容,就像Postman(Chrome应用程序)之类的东西一样,我无法检查将其伪装为text / Json的响应。
编辑
关于已接受的答案:最近提出的解决方案(UPDATE 2)为我工作(使用HTTP POST为请求提供JSON正文)。确保使用axios
(https://github.com/axios/axios)执行HTTP请求(您可以将其导入<script>
Vue文件的一部分中,如下所示:)import axios …
所以,我有一个用于上传图片的用户输入。这是一个简单的例子:
function handleImage(e){
var reader = new FileReader();
reader.onload = function(event){
var img = new Image();
img.onload = function(){
console.log (img);
}
img.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
}
Run Code Online (Sandbox Code Playgroud)
<input type="file" onchange="handleImage(event)"><br>
Run Code Online (Sandbox Code Playgroud)
如您所见,我Image ()
在console
. 我想将其转换Image
为 jpg 文件。
我知道如何获取图片的像素,但是将它发送到服务器完全是疯狂的:它太大了!
我还尝试访问存储在计算机中的 jpg 文件,但我没有实现任何目标。
我发现的唯一方法是form
像这样发送它:
<form action="anything.php" method="post" enctype="multipart/form-data">
<input type="file" name="fileToUpload" id="fileToUpload">
</form>
Run Code Online (Sandbox Code Playgroud)
在 PHP 中:
$_FILES["fileToUpload"]["tmp_name"]
Run Code Online (Sandbox Code Playgroud)
为什么不使用 JS?
我的最终目标是使用 AJAX 发送 jpg 文件。
如果您有任何问题,请告诉我。