首页 > 代码库 > ajax 文件上传

ajax 文件上传

啥也不说了,直接上代码!

<input type="file" id="file" name="myfile" onclick="clearProgressInfo()"/>
<span id="progressInfo" style="display:none;">
<progress id="progressBar" value=http://www.mamicode.com/"0" max="100">>
js代码

function UpladFile() {
	var fileObj = document.getElementById("file").files[0]; // js 获取文件对象
	var FileController = "/file/saveFile.do"; // 接收上传文件的后台地址 

	// FormData 对象
	var form = new FormData();
	form.append("author", "hooyes"); // 可以增加表单数据
	form.append("file", fileObj); // 文件对象

	// XMLHttpRequest 对象
	var xhr = new XMLHttpRequest();
	xhr.open("post", FileController, true);
	xhr.onload = function() {
		// alert("上传完成!");
	};
	
	document.getElementById('progressInfo').style.display = "";
	xhr.upload.addEventListener("progress", progressFunction, false);

	xhr.send(form);
}

function clearProgressInfo()
{
	document.getElementById('progressInfo').style.display='none';
	document.getElementById("progressBar").value = http://www.mamicode.com/0;>
java后台处理:

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.util.Streams;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartResolver;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.mvc.multiaction.MultiActionController;

import com.okcoin.util.Logs;

@Controller
@RequestMapping(value=http://www.mamicode.com/"/file/*.do")>

ajax 文件上传