您的位置:首页 > 编程语言 > Java开发

SpringMVC+AJAX+MultipartFile上传单个图片

2016-09-02 20:12 393 查看
在这里我得先吐槽一下原本已经写好的博客。。结果手贱的点了本机导入,想要导入一下外部插件提供下载的。。结果直接把整篇博客给覆盖了。。真的是泪流满面啊。。但是为了各位的方便。也让我以后开发的时候有印象写过这东西。。我还是狠下心。再写一次

SpringMVC+AJAX+MultipartFile 异步上传图片在很多博客上基本上都有写,但是基本都是东缺一块西缺一块的,昨晚就调这东西调了很久,总算成功解决了。。

要用到ajaxfileupload.js这个插件,各位可以去网上下载

但这个插件貌似在jq1.2版本以上运行,就会开始报错,因为版本有点太老,各位调用的时候会发现他前端console报找不到handleError这个方法,在各位下载完ajaxfileupload之后,要记得把下面这段代码复制进里面,放在jQuery.extend({后面,别忘了最后那个逗号

handleError: function( s, xhr, status, e )      {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || s, xhr, status, e );
}

// Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
},


准备工作做完之后,别忘了这个js导入html的script标签的时候要放在jq的下面,否则
4000
调用不了,这是一些前端小白经常犯的问题。。然后接下来提供的是html部分的代码和ajax请求代码

由于ajaxfileupload调用的时候返回的是一个text类型的字段,所以千万不要设置dataType,否则会一直接收不到信息,下面已经用$.parseJSON处理了返回的对象成json了

function upPhoto(){
var url = "xxx";//这里填请求的地址
$.ajaxFileUpload({
url : url,
type : 'POST',
fileElementId : 'test1',  //这里对应html中上传file的id
contentType:"application/json;charset=UTF-8",
success: function(data){
var str = $(data).find("body").text();//获取返回的字符串
var json = $.parseJSON(str);//把字符串转化为json对象
if(json.status){
alert("上传成功URL为" + json.url);
}
else{
alert("删除失败");
}
},
error: function(){
alert("请链接网络");
}
})
}


选择文件:<input type="file" name="file" id="test1">
<a onclick="upPhoto()">提交</a>


这样子调用前台的准备工作基本上就完成了,接下里就是Springmvc中需要的东西,由于我用的mvc框架比较老,file的处理是封装写在service里的。所以Controller往里传的是单个的file,返回的是map对象

@Controller
@RequestMapping("/file")
public class FileController extends BaseController{

@ResponseBody
@RequestMapping(value="/upPhoto",method = RequestMethod.POST)
public Map<String, String> processUpload(@RequestParam(value="file",required=false) MultipartFile file, HttpServletRequest request,HttpServletResponse response) {
Map<String, String> map = new Files().processUploadPost(file);
return map;
}

}


下面是service里的代码

targPath是上传路径

isPhotoFormat是封装的判断文件格式是否正确的方法

generateFileName是一个根据时间来生成的名字,当有多个图片上传的时候会做特殊处理

logger是一个像日志那样打印情况的,不知道的可以百度一下

public Map<String, String> processUploadPost(MultipartFile file) {
Map<String, String> map = new HashMap<String,String>();
// 判断提交的请求是否包含文件

try {
// 上传文件的返回地址
String fileUrl = "";

if (file != null) {
//获取file的名字
String fileClientName = file.getOriginalFilename();
String fileSuffix = fileClientName.substring(fileClientName.lastIndexOf(".") - 1,fileClientName.length());
if (!isPhotoFormat(fileSuffix)) {
logger.error("上传文件的格式错误=" + fileSuffix);
map.put("status", "error");
map.put("message", "格式错误,仅支持jpg|jpeg|bmp|gif|png|txt|doc|docx|xls|xlsx|csv|ppt|pptx|pdf|wps|et|dps格式'");
return map;
}

if (logger.isInfoEnabled()) {
logger.info("开始上传文件:" + file.getName());
}

String fileServerName = generateFileName(file, fileSuffix);
// 为了客户端已经设置好了图片名称在服务器继续能够明确识别,这里不改名称
File tempFile = new File(targPath+"/"+fileServerName);
//文件转换
file.transferTo(tempFile);
if (logger.isInfoEnabled()) {
logger.info("上传文件结束,新名称:" + fileServerName + ".floder:"
+ tempFile.getPath());
}

// 组装返回url,以便于ckeditor定位图片
fileUrl = targPath+"/"+fileServerName;
map.put("status", "success");
map.put("message", "上传成功");
map.put("url", fileUrl);
System.out.println("成功");
}
else{
map.put("status", "error");
map.put("message", "文件为空");
}

} catch (IOException e) {
logger.error("上传文件发生异常!", e);
map.put("status", "error");
map.put("message", "上传文件发生异常!");
} catch (Exception e) {
logger.error("上传文件发生异常!", e);
map.put("status", "error");
map.put("message", "上传文件发生异常!");
}

return map;
}


private String generateFileName(MultipartFile folder, String suffix) {
String filename;
File file;
Date date = new Date(System.currentTimeMillis());
SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
String base = format.format(date);
filename = base + "." + suffix;
file = new File(filename);
int i = 1;
while (file.exists()) {
filename = String.format("%s_%d.%s", base, i, suffix);
i++;
}
return filename;
}


public static Boolean isPhotoFormat(String fileSuffix){
if(StringUtils.equalsIgnoreCase(fileSuffix, "jpg")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "jpeg")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "bmp")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "gif")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "png")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "txt")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "doc")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "docx")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "xls")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "xlsx")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "csv")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "ppt")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "pptx")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "pdf")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "wps")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "et")
&& !StringUtils.equalsIgnoreCase(fileSuffix, "dps"))
return false;
return true;
}


以上的所有代码都完成以后,别忘了配置xml将这段xml代码扔进springmvc.xml即可,你的文件基本上就是上传成功的啦。

<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!--文件上传的指定编码格式 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小的最大值,单位是字节,1G-->
<property name="maxUploadSize" value="1000000"/>
<!-- 文件上传的临时目录 -->
<property name="uploadTempDir" value="/resource"/>
</bean>


之前有发过不是关于项目的,而是关于acm算法的,基本上我是两个事情都有同时在做,感觉都是调试代码,编辑代码,设计代码,能锻炼的都是挺多的,只希望自己能在程序猿这条路上越走越远
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐