图片上传到本地

前台

<form id="pForm" action="/product/save.do" method="post"
      enctype="multipart/form-data"><%--表单上传图片必须有:enctype="multipart/form-data",multipart/form-data 是上传二进制数据--%>

<td width="80%" class="pn-fcontent">
    <img width="100" height="100" id="allimg"/>
    <input type="file" name="picfile" οnchange="ImgUpload();"/>
    <input type="hidden" name="img.url" id="himg"/>    <!-- 回显图片的路径 -->
</td>

</form>

 

//图片上传的操作
function ImgUpload() {
    //使用jQuery的三方插件 jQuery.form.js
    var opts = {
        url: "/upload/ImgtoFastDFS.do",
        type: "post",
        dataType: "json",
        success: function (data) {
            //返回图片存储在服务器的路径来进行回显
            $("#allimg").attr("src", data.url);
            //把路径存在把隐藏域里面保存到数据库
            $("#himg").val(data.path);
        }
    };
    //提交表单
    $("#pForm").ajaxSubmit(opts);
}

 

 

 

 

后台

/**
 * 用来处理图片上传
 *
 * @author quan
 */

@Controller
public class UploadController {

    @ResponseBody//json需要的注解
    @RequestMapping("/upload/uoloadImg.do")
    //@RequestParam自动接收参数
    public void uploadImg(@RequestParam MultipartFile picfile, HttpServletRequest request, HttpServletResponse response) {
        //编写图片上传的业务逻辑方法
        //获取图片名称
        String filename = picfile.getOriginalFilename();
        //获取图片扩展名
        String ext = filename.substring(filename.lastIndexOf(".") + 1);
        //生成图片名称
        String imgName = IDUtils.genImageName();
        //生成图片的存放在服务器的路径
        String path = "/imgs/" + imgName + "." + ext;
        //获取服务器的绝对路径进行保存图片
        String url = request.getSession().getServletContext().getRealPath("") + path;

        //图片上传
        try {
            InputStream in = picfile.getInputStream();
            OutputStream out = new FileOutputStream(new File(url));
            byte[] b = new byte[1024];
            int len;
            while ((len = in.read(b)) != -1) {
                out.write(b, 0, len);
            }
            in.close();
            out.close();

            //把图片的路径使用json的格式进行返回
            JSONObject jo = new JSONObject();
            jo.put("path", path);
            response.getWriter().write(jo.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 上传图片到图片服务器
     *
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping("/upload/ImgtoFastDFS.do")
    public void uploadImgtoFastDFS(@RequestParam MultipartFile picfile, HttpServletRequest request, HttpServletResponse response) throws Exception {
        FastDFSClient fastDFSClient = new FastDFSClient("classpath:properties/fastDFS.properties");
        String filename = picfile.getOriginalFilename();
        //获取图片扩展名
        String ext = filename.substring(filename.lastIndexOf(".") + 1);
        String path = fastDFSClient.uploadFile(picfile.getBytes(), ext);    //保存到数据
        String url = SERVER_URL.IMG_SERVER + path;    //显示
        JSONObject jo = new JSONObject();
        jo.put("path", path);
        jo.put("url", url);
        response.getWriter().write(jo.toString());
    }

    /**
     * fck图片上传
     *
     * @throws Exception
     */

    @RequestMapping("/upload/productDesc.do")
    public void productDesc(HttpServletRequest request, HttpServletResponse response) throws Exception {
        FastDFSClient fastDFSClient = new FastDFSClient("classpath:properties/fastDFS.properties");
        //把request包装成MultipartRequest
        MultipartRequest multipartRequest = (MultipartRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        //遍历map拿到文件对象
        Set<Entry<String, MultipartFile>> fileSet = fileMap.entrySet();
        for (Entry<String, MultipartFile> file : fileSet) {
            MultipartFile pic = file.getValue(); //得到了文件对象
            String picAddr = fastDFSClient.uploadFile(pic.getBytes(), FilenameUtils.getExtension(pic.getName()));
            String url = SERVER_URL.IMG_SERVER + picAddr;

            //把地址写回到浏览器
            UploadResponse ok = UploadResponse.getOK(url);
            //把对象写给浏览器
            response.getWriter().print(ok);
        }

    }
}

 

Springmvc的配置

<!-- 图片上传的支持 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
   <property name="defaultEncoding" value="UTF-8"></property>
   <property name="maxUploadSize" value="5242880"></property>
</bean>

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值