我有一个Angular应用程序,它通过POST将文件上传到由Pyramid / Python处理的端点:
@Component({
selector: 'app-application',
templateUrl: 'app.application.html'
})
export class ApplicationComponent {
public uploader: FileUploader = new FileUploader({
url: MyEndPoint
});
我的金字塔服务器:
@application.post()
def job_application(request):
request.response.headerlist.extend(
(
('Access-Control-Allow-Origin', AngularClient),
('Content-Type', 'application/json'),
('Access-Control-Allow-Credentials', 'true'),
('Allow', 'GET, POST')
)
)
mailer = Mailer(host="smtp.gmail.com",
port="465", username="makeemup@gmail.com", password="password", ssl=True)
message = Message(subject="It works!",
sender="makeemup@gmail.com",
recipients=["makeemup@gmail.com"],
body="hello"
)
if request.POST:
attachment = Attachment("photo.doc", "doc/docx", str(request.body))
message.attach(attachment)
mailer.send_immediately(message, fail_silently=True)
return request.response
当我尝试将上传的文件附加到电子邮件时,WebKitFormBoundary标记将附加到文件的页眉和页脚,并以字节代码形式返回内容。如何通过Pyramid服务器将实际上传的文件附加到电子邮件地址?
答案 0 :(得分:1)
听起来你正在将POST请求的实际主体附加到文件本身,这就是为什么你的文件中存在WebKitFormBoundary标记的原因。
首先,您需要访问所需的特定内容,该内容存储在MultiDict对象中,并且可以像普通字典一样访问。
然后我会把这个内容写在某个地方,比如你的/ tmp /目录,特别是你的UNIX用户。然后从此文件路径,将电子邮件附加到金字塔邮件程序。if request.POST:
new_file = request.POST['uploadFile'].filename
input_file = request.POST['uploadFile'].file
file_path = os.path.join('/tmp', '%s.doc' % uuid.uuid4())
temp_file_path = file_path + '~'
input_file.seek(0)
with open(temp_file_path, 'wb') as output_file:
shutil.copyfileobj(input_file, output_file)
os.rename(temp_file_path, file_path)
data = open(file_path, 'rb').read()
mr_mime = mimetypes.guess_type(file_path)[0]
attachment = Attachment(new_file, mr_mime, data)
message.attach(attachment)
mailer.send_immediately(message, fail_silently=True)
希望这有帮助!