问题描述
在这里,它工作得很好,但是我没有使用收到的文件,而是使用了文件路径 我怎样才能做到这一点 我虽然将其转换为输入流会很好,但是输入流没有构造函数 请告诉我 预先感谢
@RequestMapping("/SendMail")
public String mail(@RequestParam("prescription") multipartfile prescription,@RequestParam("email") String email,HttpSession session) {
try {
customer ct=custServ.customerExists(email);
InputStream in = prescription.getInputStream();
String filename=prescription.getName();
if(ct!=null){
final String SEmail="[email protected]";
final String SPass="passowrd";
final String REmail=email;
final String Sub="Your prescription is here!";
//mail send Code
Properties props=new Properties();
props.put("mail.smtp.host","smtp.gmail.com");
props.put("mail.smtp.socketFactory.port","465");
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth","true");
props.put("mail.smtp.port","465");
Session ses=Session.getInstance(props,new javax.mail.Authenticator() {
protected PasswordAuthentication getpasswordAuthentication(){
return new PasswordAuthentication(SEmail,SPass);
}
}
);
Message message=new MimeMessage(ses);
message.setFrom(new InternetAddress(SEmail));
message.setRecipients(Message.RecipientType.TO,InternetAddress.parse(REmail));
message.setSubject(Sub);
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is your prescription here");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
messageBodyPart = new MimeBodyPart();
// File filep=new File(prescription);
DataSource source = new FileDataSource("C:\\Users\\Narci\\Desktop\\frontend\\Myqr3.jpg");
messageBodyPart.setDataHandler(new DataHandler(source));
messageBodyPart.setFileName(filename);
multipart.addBodyPart(messageBodyPart);
message.setContent(multipart);
Transport.send(message);
session.setAttribute("msg","Mail Sent successfully.");
}
else{
session.setAttribute("msg","Wrong Emial ID");
}
return "Doctor";
}
catch(Exception e) {
e.printstacktrace();
return "Error";
}
} ```
解决方法
这有点像在黑暗中拍摄,因为我不相信我真正理解这个问题。如果问题是如何使用文件代替MultipartFile并获得InputStream ,答案是使用现有的库,例如Files.newInputStream
,并以Path
作为参数。 >
Path path = Paths.get("path","to","my","file");
try (InputStream input = Files.newInputStream(path)) {
}
,
解决方案
从this other Stack Overflow answer (此答案作为社区Wiki发布),您可以在前端获取文件对象并将其转换为base64对象,如下所示:
const toBase64 = file => new Promise((resolve,reject) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => resolve(reader.result);
reader.onerror = error => reject(error);
});
async function Main() {
const file = document.querySelector('#myfile').files[0];
console.log(await toBase64(file));
}
Main();
然后,使用此Base64对象,您可以通过PUT
请求将其发送到后端,然后按照Gmail API分段上传说明将其附加到电子邮件。
我希望这对您有所帮助。让我知道您是否需要其他任何东西,或者您是否不了解。 :)