Ajax+formData非同步檔案上傳

來源:互聯網
上載者:User

標籤:lin   exce   text   ace   附件   get   request   error   .json   

前端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">

<html>

  <head>

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

    

    <title>ajax檔案上傳</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(‘提交成功!‘);

   }else{

   alert(‘提交失敗!‘);

   }

   },

   error:function(){

   alert(‘未知錯誤!‘);

   }

   });

   }

   </script>

  </head>

  

  <body>

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

   <table>

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

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

   <tr><td>附件一:</td><td><input type="file" name="ff" /></td></tr>

   <tr><td>附件二:</td><td><input type="file" name="ff2" /></td></tr>

   <tr><td colspan="2"><input type="button" onclick="add()" value="提交"></td></tr>

   </table> 

   </form>

  </body>

</html>

 

 

後端servlet java代碼:

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()){

//只能通過此形式擷取普通表單域的值,上傳檔案,表單form的enctype="multipart/form-data",是以位元據流提交資料的。所以沒法用request.getParameter("name")來擷取提交到背景普通表單域值。

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("上傳的檔案為:"+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非同步檔案上傳

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.