javascript文件上传下载

文件上传:

1、同步上传

使用 fileload 工具    http://blog.csdn.net/renfujiang/article/details/6198913


2、异步上传

A. 使用回调的方式,文件信息入库+文件上传。

        这里使用模态框,部分核心代码:    

function UploadFile() {
	// 获取文件对象
	var fileObj = $("#filePath")[0].files[0]; 		
	if (fileObj == null) {
		alert("请选择文件!");
		$scope.addItem.fileName = fileObj.name;
		return false;
	}
	
	uploadFile.append("uploadFile", fileObj);     		
	var uploadUrl = "uploadItemFile";  
	var uploadFile = new FormData();
	
	xhr.open("post", uploadUrl, true);	
	// XMLHttpRequest 对象
	var xhr = new XMLHttpRequest();

	// 定义上传完成后的回调函数
	xhr.onload = function () {
		// close函数是在模态框关闭后调用的函数会将这个参数传到主控制器的results函数中,作为回调值
		$uibModalInstance.close($scope.addItem); 
		if (xhr.status === 200 && xhr.responseText == "success") {
			alert('上传成功');
		} else {
			console.log(xhr.responseText);
			alert("上传出错了");
		}
	};
	xhr.send(uploadFile);
}


文件下载:

1、后台传给前台文件流

实现方式多种:FileUtils.readFileToByteArray (本质就是后者)或者response.getOutputStream() 借助文件流实现。

示例:

@RequestMapping(value ="/dowanloadItemFile",method = RequestMethod.GET,produces={"application/json"})/*请求到处理器功能方法的映射规则*/
public @ResponseBody ResponseEntity dowanloadItemFile(@RequestParam("filePath") String filePath, @RequestParam("fileName") String fileName) throws Exception
{
	HttpHeaders headers = new HttpHeaders(); 
	headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
	headers.setContentDispositionFormData("attachment", new String(fileName.getBytes("UTF-8"), "ISO8859-1"));

	return new ResponseEntity(FileUtils.readFileToByteArray(new File(filePath)), headers, HttpStatus.CREATED); 
}

或者

@RequestMapping(value ="/download",method = RequestMethod.GET,produces={"application/json"})/*请求到处理器功能方法的映射规则*/
public @ResponseBody void download(@RequestParam("filePath") String filePath, @RequestParam("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) throws Exception
{
	request.setCharacterEncoding("UTF-8");  
	BufferedInputStream bis = null;  
	BufferedOutputStream bos = null;  
  
	//获取下载文件
	String downLoadPath = filePath;  
  
	//获取文件的长度
	long fileLength = new File(downLoadPath).length();  

	//设置文件输出类型
	response.setContentType("application/octet-stream");  
	response.setHeader("Content-disposition", "attachment; filename=" + new String(fileName.getBytes("utf-8"), "ISO8859-1")); 
	//设置输出长度
	response.setHeader("Content-Length", String.valueOf(fileLength));  
	//获取输入流
	bis = new BufferedInputStream(new FileInputStream(downLoadPath));  
	//输出流
	bos = new BufferedOutputStream(response.getOutputStream());  
	byte[] buff = new byte[2048];  
	int bytesRead;  
	while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) 
	{  
	  bos.write(buff, 0, bytesRead);  
	}  
	System.out.println("end");
	//关闭流
	bis.close();  
	bos.close();  
}

2、前台使用浏览器本身的请求访问地址(浏览器会根据setContentType做出不同的反应)。

window.open("dowanloadItemFile?filePath=D://test//123.txt&fileName=abc.txt");






你可能感兴趣的:(JavaScript,web,javascript,文件上传)