将SVG代码转换为格式以附加到Rails中的用户
本质上,在我的应用程序中,用户可以使用JS(刺激)创建自定义SVG元素。
我的user.rb模型具有:
has_one_attached :picture
在我的attact_image_controller.js中,我可以访问SVG代码:
<svg>
<-- blah blah >
</svg>
将此代码转换为可以在我的user_controller.rb中附加的格式的最佳方法是什么?
我已经尝试将代码变成斑点并创建对象URL,但是我无法将其连接到用户(请参见下文尝试),
attach_image_controller.js
var testsvg = `<svg>
<-- blah blah >
</svg>`;
var blob = new Blob([testsvg], {type: "image/svg+xml"});
var url = URL.createObjectURL(blob);
console.log(url); // returns: blob:http://localhost:3000/15107c0d-b794-4be6-a1e0-2cf9e8f49174 and results in routing error
// As there is a routing error, this url can't be used as per below
然后将其传递给User_controller.rb:
user_controller.rb
@url = params[:url]
@user = current_user
file = URI.open(@url[5..-1])
@user.picture.attach(
io: file,
filename: @url[5..-1],
content_type: 'image/svg+xml')
edit:edit:
使事物更多在某些情况下,复杂的用户具有上传和附加图像的能力,或者生成在DOM中呈现的SVG代码,但是我希望能够连接SVG代码和上传的图像。
Essentially, in my app users can create a custom svg element using js (stimulus).
My user.rb model has:
has_one_attached :picture
in my attach_image_controller.js I can access the svg code:
<svg>
<-- blah blah >
</svg>
What is the best way to transform this code into a format that can be attached in my user_controller.rb?
I have tried turning the code into a blob and creating an object url, but I haven't been able to then attach it to a user (see below attempt)
attach_image_controller.js
var testsvg = `<svg>
<-- blah blah >
</svg>`;
var blob = new Blob([testsvg], {type: "image/svg+xml"});
var url = URL.createObjectURL(blob);
console.log(url); // returns: blob:http://localhost:3000/15107c0d-b794-4be6-a1e0-2cf9e8f49174 and results in routing error
// As there is a routing error, this url can't be used as per below
and then when passed to the user_controller.rb:
user_controller.rb
@url = params[:url]
@user = current_user
file = URI.open(@url[5..-1])
@user.picture.attach(
io: file,
filename: @url[5..-1],
content_type: 'image/svg+xml')
Edit:
To make things more complicated, in some cases, users have the ability to upload and attach an image, or generate a svg code that renders in the DOM, but I want to be able to attach both the SVG code and the uploaded image.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
附件的典型用例是我们希望将上传的文件(通常是图像,例如JPG)与模型相关联。
但是,SVG是HTML片段,它是由单个HTML元素组成的字符串(
&lt; svg&gt; ...&lt;/svg&gt;
)。因此,您可能会考虑将其简单地作为用户模型中的字符串列包括在内。但是请记住,您需要在正确渲染之前将其声明html_safe。因此,如果您使用的是ERB,则您将拥有&lt;%= user.svg_image.html_safe%&gt;
。The typical use case for attachments is when we wish to associate an uploaded file (often an image, e.g. jpg) with a model.
However the svg is an html snippet, it's a string comprised of a single html element (
<svg>... </svg>
). So you might consider simply including it as a string column in your User model. Remember, though, that you need to declare it html_safe before it will render correctly. So if you are using erb, you'll have<%= user.svg_image.html_safe %>
.