jquery.uploadify+spring mvc實現上傳圖片

一、前端頁面

1.下載jquery.uploadify

去uploadify官網(http://www.uploadify.com/download/ )下載壓縮包,解壓後放在如下路徑:

Image(1)

2.html結構

form表單的上傳控件部分:

<div class="control-group">
                <label class="control-label" for="coverImage">代表圖</label>
                <div class="controls">
                    <input type="hidden" th:field="*{coverImage}">
                    <input class="input-file" id="fileInput" type="file">
                    <img id="previewCoverImage" src="#">
                </div>
            </div>

  

3.頁面引入uploadify

<link rel="stylesheet" th:href="@{/static/uploadify/uploadify.css}”>
<script type="text/javascript" th:src="@{/static/uploadify/jquery.uploadify.js}"></script>

  

4.自定義上傳代碼

<script th:inline="javascript">
        /*<![CDATA[*/
        $(document).ready(function () {
            $("#fileInput").uploadify(
                {
                    'swf': /*[[@{/static/uploadify/uploadify.swf}]]*/,
                    'uploader': /*[[@{/upload/uploadCoverImage}]]*/, //後臺action地址
                    'queueID': 'fileQueue',
                    'auto': true,
                    'multi': false,
                    'buttonText': '上傳圖片',
                    'fileObjName': 'pic', //對應action中的參數字段名稱
                    'width': 70,
                    'height': 20,
                    'onUploadSuccess': function (file, data, response) {
                        if (data != null) {
                            $("#coverImage").val(data); //賦值給hidden控件,便於提交form表單
                            $("#previewCoverImage").attr("src",data); //複製給img控件用來預覽
                        }
                    }
                });
        });
        /*]]>*/

    </script>

  

二、站點配置

1.調整springmvc-servlet.xml文件,添加配置支持文件上傳

<!-- 支持上傳文件 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"/>

  

2.添加maven依賴

<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.1</version>
</dependency>

  

三、後臺代碼

1.controller

@Controller
@RequestMapping("/upload")
public class UploadController {

    @RequestMapping(value = "/uploadCoverImage", method = RequestMethod.POST)
    @ResponseBody
    public String uploadCoverImage(@RequestParam("pic") CommonsMultipartFile pic, HttpServletRequest req, HttpServletResponse response) throws IOException {
        //上傳文件信息
        String fileName = pic.getOriginalFilename();
        String fileType = fileName.split("[.]")[1];

        //生成文件信息
        String filePath = req.getSession().getServletContext().getRealPath(FilePathConst.COVER_IMAGE_UPLOAD);
        String uuid = UUID.randomUUID().toString().replace("-", "");
        String uuidFileName = uuid + fileName;

        //保存文件
        File f = new File(filePath + "/" + uuid + "." + fileType);
        FileUtils.uploadFile(pic.getInputStream(), uuidFileName, filePath);

        return SiteConst.SITE_DOMAIN + FilePathConst.COVER_IMAGE_UPLOAD + uuidFileName;
    }
}

  

2.FileUtils工具類

public class FileUtils {
    public static void uploadFile(InputStream is, String fileName, String filePath) {
        FileOutputStream fos = null;
        BufferedOutputStream bos = null;
        BufferedInputStream bis = null;
        File file = new File(filePath);
        if (!file.exists()) {
            file.mkdirs();
        }

        File f = new File(filePath + "/" + fileName);
        try {
            bis = new BufferedInputStream(is);
            fos = new FileOutputStream(f);
            bos = new BufferedOutputStream(fos);

            byte[] bt = new byte[4096];
            int len;
            while ((len = bis.read(bt)) > 0) {
                bos.write(bt, 0, len);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != bos) {
                    bos.close();
                    bos = null;
                }

                if (null != fos) {
                    fos.close();
                    fos = null;
                }
                if (null != is) {
                    is.close();
                    is = null;
                }

                if (null != bis) {
                    bis.close();
                    bis = null;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章