基于HTML5的多图Ajax上传
最近做的东西一直是与文件的上传有关。在自己做项目的也遇到了很多问题。比如多图上传等。网上也搜了一阵子,但是没有自己想要的那种效果。最后只能自己动手写了个基于HTML5的多图Ajax上传。页面的插件来自ISUX的一位大神的。本来这个是前几周就要发的,但因为手头工作忙,没有时间和大家分享。抱歉哦!
这个例子是利用Html5 + Ajax上传文件。利用Spring MVC框架做的。
[caption id="" align="aligncenter" width="593"]
基于HTML5的多图Ajax上传(首页)[/caption]
[caption id="" align="aligncenter" width="644"]
基于HTML5的多图Ajax上传(选择上传文件)[/caption]
[caption id="" align="aligncenter" width="644"]
基于HTML5的多图Ajax上传(上传中)[/caption]
[caption id="" align="aligncenter" width="659"]
基于HTML5的多图Ajax上传(上传完成)[/caption]
好了,这就是大致上的效果图。下面贴上关键的代码。
这个是controller的具体实现代码。
package com.baikeyang.controller;
import java.io.File;
import java.io.FileOutputStream;
import javax.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baikeyang.utils.FileUtils;
import com.baikeyang.utils.RandomUtils;
@Controller
@Scope(value = "request")
public class TestController {
/**
* 文件上传操作
* */
@ResponseBody
@RequestMapping(method = RequestMethod.POST, value = "/add-file.html")
public String addFile(HttpServletRequest request,
@RequestParam(value = "file", required = true) MultipartFile file) throws Exception {
String newFileName = "";
String urlNetPath = "";
if (!file.isEmpty()) {
String myappPath = request.getSession().getServletContext().getRealPath("/");
//D:\Program Files\Tomcat\apache-tomcat-7.0.47\webapps\ssm\ 获取应用目录的服务器路径
String filePath = myappPath + "upload\\"; //获取应用目录的文件上传目录
String fileName = file.getOriginalFilename(); //获取文件名字
String newFileType = FileUtils.getFileType(fileName);
try {
if (request instanceof MultipartHttpServletRequest) {
byte[] bytes = file.getBytes();
String fileNameRandom = RandomUtils.getRandomFileName();
File folder = new File(filePath);
if (!folder.exists()) {
folder.mkdir();
}
newFileName = filePath + fileNameRandom + '.'+ newFileType;
FileOutputStream fos = new FileOutputStream(newFileName);
fos.write(bytes); // 写入文件
fos.close();
urlNetPath = "upload/" + fileNameRandom + '.'+ newFileType;
}
} catch (Exception e) {
e.printStackTrace();
}
}
return urlNetPath;
}
}配置文件什么的,在这里就不贴了。如果大家想看看源代码的话,就去百度网盘去下载哦!直接把项目导入到MyEclipse中就可以看到效果哦!
百度网盘下载地址:http://pan.baidu.com/s/1qWprRD6
"现在的我一贫如洗" :razz:
博客不错呀 友情链接联系我
好的哦!亲!
真不知道,还有这么好心的博主 支持