以前有在網上找ajax上傳圖片的資料,大部分的人寫得都是用jQuery,可是在這裏用JQuery就大才小用了,因此我就本身寫了,先上圖。html
由上圖,首先點擊上面的選擇文件,在選擇圖片以後,將會自動上傳圖片到服務器,而且返回圖片名字和圖片在服務器的路徑,而後在頁面顯示文件名字和圖片。java
源碼:http://download.csdn.net/detail/nsguf/9851189react
React中:ajax
1 import React from 'react'; 2 import Http from './http' 3 4 const URL = 'http://localhost:8080/fileuploadExample/UploadServlet'; 5 6 export default class App extends React.Component { 7 constructor(props) { 8 super(props); 9 10 this.state = { 11 uploadedFile: "", 12 uploadedFileGetUrl: '' 13 }; 14 } 15 16 error() { 17 alert('error') 18 } 19 20 callback(result) { 21 this.setState({ 22 uploadedFile: result.uploadedFile, 23 uploadedFileGetUrl: result.uploadedFileGetUrl 24 }); 25 } 26 27 handleImageUpload(e) { 28 e.preventDefault() 29 let file = e.target 30 Http.post(URL, file, this.callback.bind(this), this.error) 31 } 32 33 render() { 34 return ( 35 <div> 36 <input type="file" onChange={this.handleImageUpload.bind(this)}/> 37 <div> 38 {this.state.uploadedFileGetUrl === '' ? null : 39 <div> 40 <p>{this.state.uploadedFile}</p> 41 <img src={this.state.uploadedFileGetUrl} alt="你選擇的圖片"/> 42 </div>} 43 </div> 44 </div> 45 ) 46 } 47 }
本身封裝的Ajax代碼:apache
var Http = (function() { var http = {}; if (typeof window.XMLHttpRequest === "undefined") { window.XMLHttpRequest = function() { // 若是是i5就用Microsoft,其餘就用Msxml2 return new window.ActiveXObject(navigator.userAgent .indexOf("MSIE 5") >= 0 ? "Microsoft.XMLHTTP" : "Msxml2.XMLHTTP"); }; } http.post = function(url, data, callback, error) { if (typeof data === "function") {//data能夠不穿值 callback = data; data = null; } var timeout = setTimeout(function() {//超時設置 error(); }, 10000); var xhr = new XMLHttpRequest(); xhr.open('post', url); xhr.onreadystatechange = function() { if (xhr.readyState === 4) { clearTimeout(timeout);//清除超時 if (xhr.status === 200){ //alert(xhr.responseText); callback(JSON.parse(xhr.responseText));//調用回調函數 } else { error(); } xhr = null;// 刪除對象,防止內存溢出 } }; xhr.onerror = function() {//若是產生了錯誤 clearTimeout(timeout); error(); }; xhr.send(http.formDataCode(data)); }; http.formDataCode = function(data) { var fd = new FormData(); if (!data) { return null; } for ( var key in data) { if(data.files){ var file=data.files[0]; fd.append("image", file); }else{ fd.append(key, data[key]); } } return fd; } return http; })(); export default Http
在java後臺上傳圖片方面,網上有不少例子均可以用,我借鑑的是http://blog.csdn.net/thc1987/article/details/15341201這篇,有興趣能夠看一下:json
package com.example; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.List; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * Servlet implementation class UploadServlet */ @WebServlet("/UploadServlet") public class UploadServlet extends HttpServlet { private static final long serialVersionUID = 1L; // 保存文件的目錄 private static String PATH_FOLDER = "/"; // 存放臨時文件的目錄 private static String TEMP_FOLDER = "/"; /** * @see HttpServlet#HttpServlet() */ public UploadServlet() { super(); // TODO Auto-generated constructor stub } @Override public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub super.init(); ServletContext servletCtx = config.getServletContext(); // 初始化路徑 // 保存文件的目錄 PATH_FOLDER = servletCtx.getRealPath("/upload"); // 存放臨時文件的目錄,存放xxx.tmp文件的目錄 TEMP_FOLDER = servletCtx.getRealPath("/uploadTemp"); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setHeader("Access-Control-Allow-Origin", "http://localhost:3000"); response.setHeader("Access-Control-Allow-Credentials", "true"); request.setCharacterEncoding("utf-8"); // 設置編碼 response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); // 得到磁盤文件條目工廠 DiskFileItemFactory factory = new DiskFileItemFactory(); // 若是沒如下兩行設置的話,上傳大的 文件 會佔用 不少內存, // 設置暫時存放的 存儲室 , 這個存儲室,能夠和 最終存儲文件 的目錄不一樣 /** * 原理 它是先存到 暫時存儲室,而後在真正寫到 對應目錄的硬盤上, 按理來講 當上傳一個文件時,實際上是上傳了兩份,第一個是以 .tem * 格式的 而後再將其真正寫到 對應目錄的硬盤上 */ factory.setRepository(new File(TEMP_FOLDER)); // 設置 緩存的大小,當上傳文件的容量超過該緩存時,直接放到 暫時存儲室 factory.setSizeThreshold(1024 * 1024); // 高水平的API文件上傳處理 ServletFileUpload upload = new ServletFileUpload(factory); try { // 提交上來的信息都在這個list裏面 // 這意味着能夠上傳多個文件 // 請自行組織代碼 List<FileItem> list = upload.parseRequest(request); // 獲取上傳的文件 FileItem item = getUploadFileItem(list); // 獲取文件名 String filename = getUploadFileName(item); // 保存後的文件名 String saveName = new Date().getTime() + filename.substring(filename.lastIndexOf(".")); // 保存後圖片的瀏覽器訪問路徑 String picUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/upload/" + saveName; System.out.println("存放目錄:" + PATH_FOLDER); System.out.println("文件名:" + filename); System.out.println("瀏覽器訪問路徑:" + picUrl); // 真正寫到磁盤上 item.write(new File(PATH_FOLDER, saveName)); // 第三方提供的 PrintWriter writer = response.getWriter(); System.out.print("{"); System.out.print("uploadedFile:"+ "\"" + filename + "\""); System.out.print(",uploadedFileGetUrl:\"" + picUrl + "\""); System.out.print("}"); JSONObject result = new JSONObject(); result.put("uploadedFile", filename); result.put("uploadedFileGetUrl", picUrl); writer.write(result.toString()); writer.close(); } catch (Exception e) { e.printStackTrace(); /* * PrintWriter writer = response.getWriter(); writer.print("{"); * writer.print("error:"+e.toString()); writer.print("}"); * writer.close(); */ } } private FileItem getUploadFileItem(List<FileItem> list) { for (FileItem fileItem : list) { if (!fileItem.isFormField()) { return fileItem; } } return null; } private String getUploadFileName(FileItem item) { // 獲取路徑名 String value = item.getName(); System.out.println(value + ":value"); // 索引到最後一個反斜槓 int start = value.lastIndexOf("/"); // 截取 上傳文件的 字符串名字,加1是 去掉反斜槓, String filename = value.substring(start + 1); return filename; } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
以上java代碼這裏修改了這幾點:跨域
一、插入response.setHeader("Access-Control-Allow-Origin","http://localhost:3000");
response.setHeader("Access-Control-Allow-Credentials", "true");瀏覽器
這兩行代碼,進行跨域,固然,這個可能不安全緩存
二、安全
JSONObject result = new JSONObject();
result.put("uploadedFile", filename);
result.put("uploadedFileGetUrl", picUrl);
writer.write(result.toString());
在這裏,頁面和服務器之間使用json數據傳輸的
本人第一次發佈博文,請批評指正~~~