1. 导入JQuery相关JS文件
<script src="<@full_path path="js/jquery.js"/>" type="text/javascript"></script>
<script src="<@full_path path="js/ajaxfileupload.js"/>" type="text/javascript"></script>
2. 页面调用以及JS代码:
<th>图片上传:</th>
<td>
<A hideFocus class="addfileA" id="aComposeAttach" href="#" >
<INPUT hideFocus class=addfileI type=file size=1 name="file" id="defaultIconUpload" οnchange="return ajaxUpload('defaultIconUpload','defaultIconImg','defaultIcon');">
</A>
<img width="150" height="150" src="<@full_path path="img/no_picture.gif"/>" id="defaultIconImg" />
<input type="hidden" maxlength="20" class="" id="defaultIcon" name="defaultIcon" />
</td>
//上传方法
function ajaxUpload(id,imgId,hiddId){
var content= document.getElementById(id).value;
if(content.length==''){
alert("请选择图片!");
return false;
}
//webapp/
var baseUrl = "<@full_path path="/"/>";
//alert("baseUrl is " + baseUrl + ",id is " + id);
$.ajaxFileUpload
(
{
url: baseUrl + 'upload/app', //你处理上传文件的服务端
secureuri:false,
fileElementId:id,
dataType: 'json',
success: function (data, status)
{
$("#"+imgId).attr("src",baseUrl+"uploads/"+data.file_path);
$("#"+hiddId).val("uploads/"+data.file_path);
//alert("上传成功!");
},
error: function (data, status, e)
{
alert("上传图片失败!");
}
}
);
return false;
}
3. 后台操作JAVA代码:
@RequestMapping("/upload")
@Controller
public class FileUploadController {
private final static Logger logger=LoggerFactory.getLogger(FileUploadController.class);
public static class FileUploadResp{
/**
* 结果:0 表示成功;1 表示失败
*/
private int result;
/**
* 结果说明
*/
private String desc;
/**
* 上传文件保存路径
*/
@JsonProperty("file_path")
private String filePath;
public FileUploadResp(){}
public FileUploadResp(int result, String desc) {
super();
this.result = result;
this.desc = desc;
}
public FileUploadResp(String filePath) {
super();
this.result = 0;
this.desc = "上传成功";
this.filePath = filePath;
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
@JsonIgnore
public String getFilePath() {
return filePath;
}
public void setFilePath(String filePath) {
this.filePath = filePath;
}
public String toString(){
return ToStringBuilder.reflectionToString(this);
}
}
@RequestMapping(value="/{module}/{resType}",method = RequestMethod.POST)
public @ResponseBody Object uploadToTmp(HttpServletRequest request,@PathVariable String module,@PathVariable String resType,@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
String relPathOfSavedDir=module+"/"+resType+"/";
try {
File savedDir = prepareSavedDir(request, relPathOfSavedDir);
String savedFileName=getSavedFileName(file.getOriginalFilename());
file.transferTo(new File(savedDir,savedFileName));
return new FileUploadResp(relPathOfSavedDir+savedFileName);
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
return new FileUploadResp(1,e.getLocalizedMessage());
}
}
@RequestMapping(value="/menu/{resType}/{baseLine}/{org}/{section}",method = RequestMethod.POST)
public @ResponseBody Object uploadForMenu(HttpServletRequest request,@PathVariable String resType,@PathVariable String baseLine,@PathVariable String org,@PathVariable String section,@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
String relPathOfSavedDir="menu/"+resType+"/"+baseLine+"/"+org+"/"+section+"/";
try {
File savedDir = prepareSavedDir(request, relPathOfSavedDir);
String savedFileName=getSavedFileName(file.getOriginalFilename());
file.transferTo(new File(savedDir,savedFileName));
return new FileUploadResp(relPathOfSavedDir+savedFileName);
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
return new FileUploadResp(1,e.getLocalizedMessage());
}
}
@RequestMapping(value="/app",method = RequestMethod.POST)
public @ResponseBody Object uploadForApp(HttpServletRequest request,@RequestParam("file") MultipartFile file) throws IllegalStateException, IOException {
String relPathOfSavedDir="app/";
try {
File savedDir = prepareSavedDir(request, relPathOfSavedDir);
String savedFileName=getSavedFileName(file.getOriginalFilename());
file.transferTo(new File(savedDir,savedFileName));
return new FileUploadResp(relPathOfSavedDir+savedFileName);
} catch (Exception e) {
logger.error(e.getLocalizedMessage(), e);
return new FileUploadResp(1,e.getLocalizedMessage());
}
}
private File prepareSavedDir(HttpServletRequest request,String relativePath) throws Exception{
File dir=new File(request.getSession().getServletContext().getRealPath("/uploads/"+relativePath));
if(!dir.exists()){
if(!dir.mkdirs()){
throw new Exception("创建保存目录失败");
}
}
return dir;
}
private String getSavedFileName(String origFileName){
return DateHelper.getCurrentTimeStamp("yyyyMMddHHmmss") +"-"+RandomStringUtils.randomNumeric(5)+"."+FilenameUtils.getExtension(origFileName);
}
}