最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Ajax using file upload - Stack Overflow

programmeradmin5浏览0评论

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.

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.

Share Improve this question edited Aug 26, 2012 at 18:04 skynet 9,9085 gold badges45 silver badges52 bronze badges asked Feb 2, 2009 at 6:32 praveenjayapalpraveenjayapal 38.5k31 gold badges74 silver badges74 bronze badges
Add a comment  | 

4 Answers 4

Reset to default 14 +100

Check these questions:

  • JavaScript file uploads
  • How can I get Gmail-like file uploads for my web app?
  • What is the best multiple file JavaScript / Flash file uploader?

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>

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.

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.

发布评论

评论列表(0)

  1. 暂无评论