首页 > Web开发 > 详细

web端 图片上传

时间:2015-09-17 10:11:16      阅读:248      评论:0      收藏:0      [点我收藏+]

需要插件:ajaxfileupload.js  commons-fileupload-1.3.1.jar
web端:
  

<form id="saveForm" method="post" enctype="multipart/form-data">
<label>广告图片:</label><input  type="file" id="image1" name="image1" data-options="required:true" />
                             <img src="../../imgSrc/aaaaaa.jpg" id="img" width="100px",height="100px"/>
                              <input type="button" id="sub" value="上传"/>
</form>
<script type="text/javascript">
$(function(){
    $("#sub").click(function(){
        $.ajaxFileUpload({  
            url:upload.do,  
            secureuri:false,  
            fileElementId:image1,//file标签的id  
            dataType: json,//返回数据的类型  
            success: function (data) {  
                $("#img").attr("src","../../imgSrc/"+data);
            },  
        });
    });
});
</script>

java后台:
  

    @RequestMapping("upload")
    @ResponseBody
    public  String upload(@RequestParam("image1") MultipartFile file,HttpServletRequest req){
//         String saveFilePath = req.getServletContext().getRealPath("/WEB-INF/upload");
        String saveFilePath=Constant.savePath;
        try {
            if (!file.isEmpty()) { 
                // 获取图片的文件名
                String fileName = file.getOriginalFilename();
                // 获取图片的扩展名
                String extensionName = fileName
                        .substring(fileName.lastIndexOf(".") + 1);
                // 新的图片文件名 = 获取时间戳+"."图片扩展名
                String newFileName = String.valueOf(System.currentTimeMillis()) + "." + extensionName;
                ImgUtils.saveFile(newFileName, file, saveFilePath);    
                 return newFileName;  
            }else{
                 return "exception";
            }
    } catch (Exception e) {
        e.printStackTrace();
        return "Exception";
    } 
    }
    public static void saveFile(String newFileName, MultipartFile filedata,String saveFilePath) {
        // TODO Auto-generated method stub
        // 根据配置文件获取服务器图片存放路径
        /* 构建文件目录 */
        File fileDir = new File(saveFilePath);
        if (!fileDir.exists()) {
            fileDir.mkdirs();
        }
        try {
            FileOutputStream out = new FileOutputStream(saveFilePath + "\\"
                    + newFileName);
            // 写入文件
            out.write(filedata.getBytes());
            out.flush();
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
    }

tomcat:
  

      <Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true">
        <Context docBase="D:\upload" path="/imgSrc"/>

 

web端 图片上传

原文:http://www.cnblogs.com/jinjixia/p/4815377.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!