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.

skynet
  • 9,898
  • 5
  • 43
  • 52
praveenjayapal
  • 37,683
  • 30
  • 72
  • 72

4 Answers4

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>
Kamil Kiełczewski
  • 85,173
  • 29
  • 368
  • 345
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.

Techmaddy
  • 4,586
  • 5
  • 28
  • 33
  • In case you need a basic Ajax reference, http://techmaddy.blogspot.com/2008/01/for-those-who-feel-ajax-is-diffcult-to.html – Techmaddy Feb 02 '09 at 06:46
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.

miceuz
  • 3,327
  • 5
  • 29
  • 33