jsp代码
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>user_list</title>
<script type="text/javascript" src="js/jquery.js" ></script>
<!-- <script type="text/javascript" src="js/Ajax.js" ></script> -->
<script type="text/javascript" src="js/ajaxfileupload.js" ></script>
</head>
<body>
<div id="result"></div>
<img id="uploadImage" src="http://www.firefox.com.cn/favicon.ico">
选择文件:<input type="file" id="uploadFile" name="myfiles"/> <br/>
<input type="button" value="上传" onclick="upload();" />
<input type="reset" value="取消" />
<table id="color_manage_datagrid"></table>
<form action="filedown.do" method="post">
<input type="text" id="filename" name="filename"/>
<input type="submit" value="下载" />
</form>
<script type="text/javascript">
/* $(document).ready(function() {
$.ajax({
url:"test/ajax.do",
type:"post",
dataType:"text",
data:{
name:"zhangsan"
},
success:function(responseText){
alert(responseText);
},
error:function(){
alert("system error");
}
});
}); */
function upload(){
$.ajaxFileUpload
(
{
url:'fileUpload1.do?uname=d',
secureuri:false,
fileElementId:'uploadFile',
dataType: 'text',
success:function(data, status){ //服务器响应成功时的处理函数
data = data.replace(/<pre.*?>/g, ''); //ajaxFileUpload会对服务器响应回来的text内容加上<pre style="....">text</pre>前后缀
data = data.replace(/<PRE.*?>/g, '');
data = data.replace("<PRE>", '');
data = data.replace("</PRE>", '');
data = data.replace("<pre>", '');
data = data.replace("</pre>", ''); //本例中设定上传文件完毕后,服务端会返回给前台[0`filepath]
if(data.substring(0, 1) == 0){ //0表示上传成功(后跟上传后的文件路径),1表示失败(后跟失败描述)
$("img[id='uploadImage']").attr("src", data.substring(2));
$('#result').html("图片上传成功<br/>");
}else{
$('#result').html('图片上传失败,请重试!!');
}
},
error: function (data, status, e)
{
alert("【服务器异常,请连续管理员!2】");
}
}
);
return false;
}
</script>
</body>
</html>
controller端代码
/**
* 上传文件
*
* 这里这里用的是MultipartFile[] myfiles参数,所以前台就要用<input type="file" name="myfiles"/>
* 上传文件完毕后返回给前台[0`filepath],0表示上传成功(后跟上传后的文件路径),1表示失败(后跟失败描述)
*/
@RequestMapping(value="/fileUpload1")
public Json addUser(UpFile upfile ,@RequestParam("uname") String uname, @RequestParam MultipartFile[] myfiles, HttpServletRequest request, HttpServletResponse response) throws IOException{
//可以在上传文件的同时接收其它参数
System.out.println("收到用户[" + uname + "]的文件上传请求");
//如果用的是Tomcat服务器,则文件会上传到\\%TOMCAT_HOME%\\webapps\\YourWebProject\\upload\\文件夹中
//这里实现文件上传操作用的是commons.io.FileUtils类,它会自动判断/upload是否存在,不存在会自动创建
String realPath = "D:\\upload";
//设置响应给前台内容的数据格式
response.setContentType("text/plain; charset=UTF-8");
//设置响应给前台内容的PrintWriter对象
PrintWriter out = response.getWriter();
//上传文件的原名(即上传前的文件名字)
String originalFilename = null;
//如果只是上传一个文件,则只需要MultipartFile类型接收文件即可,而且无需显式指定@RequestParam注解
//如果想上传多个文件,那么这里就要用MultipartFile[]类型来接收文件,并且要指定@RequestParam注解
//上传多个文件时,前台表单中的所有<input type="file"/>的name都应该是myfiles,否则参数里的myfiles无法获取到所有上传的文件
for(MultipartFile myfile : myfiles){
if(myfile.isEmpty()){
out.print("1`请选择文件后上传");
out.flush();
return null;
}else{
originalFilename = myfile.getOriginalFilename();
upfile.setFilename(originalFilename);
upfile.setFileroute(realPath+"\\"+originalFilename);
// SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
upfile.setFiledate(new Date());
Json json = new Json();
System.out.println(new Date());// new Date()为获取当前系统时间
System.out.println("文件原名: " + originalFilename);
System.out.println("文件名称: " + myfile.getName());
System.out.println("文件长度: " + myfile.getSize());
System.out.println("文件类型: " + myfile.getContentType());
System.out.println("文件路径: " + realPath+"\\"+originalFilename);
System.out.println("========================================");
try {
//这里不必处理IO流关闭的问题,因为FileUtils.copyInputStreamToFile()方法内部会自动把用到的IO流关掉
//此处也可以使用Spring提供的MultipartFile.transferTo(File dest)方法实现文件的上传
FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(realPath, originalFilename));
json = upfileService.add(json, upfile);
} catch (IOException e) {
System.out.println("文件[" + originalFilename + "]上传失败,堆栈轨迹如下");
e.printStackTrace();
out.print("1`文件上传失败,请重试!!");
out.flush();
return null;
}
}
}
//此时在Windows下输出的是[D:\Develop\apache-tomcat-6.0.36\webapps\AjaxFileUpload\\upload\愤怒的小鸟.jpg]
//System.out.println(realPath + "\\" + originalFilename);
//此时在Windows下输出的是[/AjaxFileUpload/upload/愤怒的小鸟.jpg]
//System.out.println(request.getContextPath() + "/upload/" + originalFilename);
//不推荐返回[realPath + "\\" + originalFilename]的值
//因为在Windows下<img src="file:///D:/aa.jpg">能被firefox显示,而<img src="D:/aa.jpg">firefox是不认的
out.print("0`" + request.getContextPath() + "/upload/" + originalFilename);
out.flush();
return null;
}
/**
* 下载文件
*
*
*/
@RequestMapping(value="/filedown")
public ResponseEntity<byte[]> download(@RequestParam("filename") String filename) throws IOException {
System.out.println(filename);
String path="D:\\upload\\"+filename;
System.out.println(path);
File file=new File(path);
HttpHeaders headers = new HttpHeaders();
String fileName=new String(filename.getBytes("UTF-8"),"iso-8859-1");//为了解决中文名称乱码问题
headers.setContentDispositionFormData("attachment", fileName);
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
headers, HttpStatus.CREATED);
}