SpringMVC+jQuery(ajaxSubmit) 异步上传图片

[b]备忘[/b]

前端引入jQuery以及jquery.form.js


<script type="text/javascript" src="js/jquery-1.8.2.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript">

function upload(){
var optionsThumbnail = {
url: "http://localhost:8080/#",
type: 'POST',
async: false,
dataType: 'json',
success: function (data) {
if (data.status == 1) {
$("#pic").attr("src",data.filePath);
}
else {
alert("系统错误!");
}
}, error: function (data) {
alert("上传文件出错!");
}
};

if ($('#file').val() != "") {
$("#guestPortraitForm").ajaxSubmit(optionsThumbnail);
}
}

</script>


<form id="guestPortraitForm" enctype="multipart/form-data"
method="post" name="guestPortraitForm">
<table class="searchtable">
<tr>
<td class="bg_gray">附件:</td>
<td>
<input type="file" id="file" name="file"/>
</td>
</tr>
<tr>
<td colspan="2">
<input type="button" value="上传" onclick="upload();"/>
</td>
</tr>
</table>
</form>



后台Controller:

@RequestMapping(value = "/upload/{type}", method = RequestMethod.POST)
@ResponseBody
public Map<String,Object> upload(@RequestParam final MultipartFile file, final @PathVariable String type, final HttpServletRequest request, final HttpServletResponse response)
throws Exception{
Map<String,Object> data = new HashMap<String,Object>();
try {
String abstractFilePath = generateAbstractPath(file.getOriginalFilename(), type);
String absolutePath = generateAbsolutePath(abstractFilePath);

String cdnPath = "http://localhost:8080/2/";
String filePath = cdnPath+abstractFilePath;

FileUtils.save(absolutePath, file.getInputStream());

data.put(Constants.FILE_PATH, filePath);
data.put(Constants.RESULT_STATUS, Constants.RESULT_SUCCEED);
} catch (Exception e) {
data.put(Constants.RESULT_STATUS, Constants.RESULT_FAILED);
}
return data;
}

private String generateAbstractPath(String originalFileName, String type) {
String suffix = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
String fileName = new Date().getTime() + "_" + new Random().nextInt(100) + "." + suffix;
return type+"/"+fileName;
}


private String generateAbsolutePath(String abstractFilePath) {
String uploadPath = Constants.FILE_UPLOAD_BASE_PATH + abstractFilePath;
return uploadPath;
}



ie浏览器下,返回json出现提示下载的问题:http://www.blogjava.net/iamlibo/archive/2013/11/21/406646.html


图片查看时,配置一下虚拟目录。

<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
<Context docBase="D:/opt/csa" path="/csa" reloadable="true"/>
</Host>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值