备忘
前端引入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>