5

I am creating mail page for sending mails. I need to attach some file before sending. How could I do this using AJAX? Initially I need to store those files in server and then I have to send the mail. These actions are done with in a single send button.

4 Answers 4

14
+100

Check these questions:

Sign up to request clarification or add additional context in comments.

Comments

1

Look on below snippet which send text data and attached multi-files. The content-type='multipart/form-data' is set by browser automatically, the file name is added automatically too to filename FormData parameter (and can be easy read by server).

async function sendEmail() {
  let formData = new FormData();
  let msg = { message: emailText.value };
 
  formData.append("email", JSON.stringify(msg)); 
  [...attachment.files].map( (file,i) => formData.append("file"+i, file) );

  try {
    await fetch('your/api/upload/email', { method: "POST", body: formData });
    alert("Email was send!");
  } catch(e) {
    alert("Problem with email sending");
  }
}
<textarea id="emailText" placeholder="Type message here"></textarea><br>

<input type="file" id="attachment" multiple /><br><br>
<input type="button" value="Send email" onclick="sendEmail()" />

<br><br><span style="color:red">In this snippet API not exists so exception will be thrown but you can look on your request in:<br> chrome console> network tab</span>

Comments

0

I hope you know how do the normal upload. Call the upload/Reading and updating the file when click the button by using the ajax call. You have to send the local system file path as the input and then the response should contain the path in the server or error. Update the attachment link with the response in case there are no errors.

1 Comment

In case you need a basic Ajax reference, techmaddy.blogspot.com/2008/01/…
0

You should dynamically create a hidden iframe in your DOM and set the target of your upload form to this iframe. dont forget to set form method to POST.

you could do both uploading and message field filling in one go.

you should definitely check ready components doing this for the javascript library of your choice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.