Ajax+formdata Asynchronous File Upload

Source: Internet
Author: User

front-end JSP:

<%@ page language="java" import="java.util.*" pageencoding="UTF-8"%>

<%

String path = Request.getcontextpath ();

String basepath = request.getscheme () + "://" +request.getservername () + ":" +request.getserverport () +path+ "/";

%>

<! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

<base href="<%=basePath%>">

<title>Ajax file uploads </title>

<script type="Text/javascript" src="Js/jquery-2.1.1.js"></script>

<script type="Text/javascript">

function Add () {

var formdata=New formdata ($ ("#frm") [0]);

$.ajax ({

Type: ' Post ',

URL: ' Ajaxupload.do ',

Data:formdata,

DataType: ' JSON ',

ContentType:false,

ProcessData:false,

Success:function(data) {

var result=data.result;

if (result== ' 1 ') {

Alert (' Submit success! ‘);

}Else{

Alert (' Submit failed! ‘);

}

},

Error:function() {

Alert (' Unknown error! ‘);

}

});

}

</script>

<body>

<form method="POST" id="frm" >

<table>

<tr><td> title : </td><td><input type="text" name="title" /> </td></tr>

<tr><td> content : </td><td><input type="text" name="content" /> </td></tr>

<tr><td> Annex I : </td><td><input type="file" name="FF" />< /td></tr>

<tr><td> Annex II : </td><td><input type="file" name="FF2" / ></td></tr>

<TR><TD colspan="2"><input type="button" onclick= "Add ()" Value="Submit"> </td></tr>

</table>

</form>

</body>

back-end servlet java code :

Package servlet;

Import Java.io.File;

Import java.io.IOException;

Import Java.io.PrintWriter;

Import java.util.List;

Import Java.util.UUID;

Import javax.servlet.ServletException;

Import Javax.servlet.http.HttpServlet;

Import Javax.servlet.http.HttpServletRequest;

Import Javax.servlet.http.HttpServletResponse;

Import Org.apache.commons.fileupload.FileItem;

Import Org.apache.commons.fileupload.disk.DiskFileItemFactory;

Import Org.apache.commons.fileupload.servlet.ServletFileUpload;

Import Org.json.JSONObject;

public class Ajaxuploadservlet extends HttpServlet {

public void doget (HttpServletRequest request, httpservletresponse response)

Throws Servletexception, IOException {

This.dopost (request, response);

}

public void DoPost (HttpServletRequest request, httpservletresponse response)

Throws Servletexception, IOException {

Response.setcontenttype ("text/html");

PrintWriter out = Response.getwriter ();

Diskfileitemfactory factory=new diskfileitemfactory ();

Servletfileupload upload=new servletfileupload (Factory);

Jsonobject js=new jsonobject ();

String title= "";

String content= "";

try {

List<fileitem> items=upload.parserequest (Request);

for (Fileitem Item:items) {

if (Item.isformfield ()) {

only in this form can get the value of the normal form field , upload the file, form form of the enctype= "Multipart/form-data", is to submit data in binary data stream. Therefore, you cannot use Request.getparameter ("name") to get the normal form field values that are submitted to the background.

if ("title". Equals (Item.getfieldname ())) {

Title=item.getstring ("UTF-8");

}else if ("Content". Equals (Item.getfieldname ())) {

Content=item.getstring ("UTF-8");

}

}else{

String Filename=item.getname ();

System.out.println (" uploaded file :" +filename);

String Path=request.getrealpath ("/upload");

File F=new file (path+ "/" +uuid.randomuuid () + "-" +filename);

Item.write (f);

Js.put ("Result", "1");

}

}

System.out.println ("title:" +title+ ", Content:" +content);

} catch (Exception e) {

E.printstacktrace ();

}

Out.write (Js.tostring ());

}

}

Ajax+formdata Asynchronous File Upload

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.