Spring MultipartFile 文件上传【注解】& JQuery uploader plugin

首先准备工作:
我用的是Spring 3.02 +Gson1.71+JQuery 1.52+JQuery Uploader Plugin https://github.com/blueimp/jQuery-File-Upload
applicationContext.xml:
<!-- 激活spring的注解. -->
    <context:annotation-config />

    <!-- 扫描注解组件并且自动的注入spring beans中.
    例如,他会扫描@Controller 和@Service下的文件.所以确保此base-package设置正确. -->
    <context:component-scan base-package="com.swind.web" />

    <!-- 配置注解驱动的Spring MVC Controller 的编程模型.注:次标签只在 Servlet MVC工作! -->
    <mvc:annotation-driven />

dispatcher-servlet.xml
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <value>104857600</value>
        </property>
        <property name="maxInMemorySize">
            <value>4096</value>
        </property>
        <property name="defaultEncoding">
            <value>UTF-8</value>
        </property>
    </bean>


web.xml:
   <servlet-mapping>
        <servlet-name>Dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

服务端:Controller、Service都是从网上Copy来的,加以修改。
Controller:
为JQuery uploader 删除增加了一个handleDelete方法。
package com.swind.web.controller;

import com.google.gson.Gson;
import com.swind.common.GlobalVariable;
import com.swind.web.model.FileModel;
import com.swind.web.service.UploadService;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.support.DefaultMultipartHttpServletRequest;

@Controller
public class UploadController {

    @Resource(name = "uploadService")
    private UploadService uploadService;

    /**
     * 描述 : <事先就知道确切的上传文件数目>. <br>
     *<p>

     * @param file1
     * @param file2
     * @param model
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/upload.single", method = RequestMethod.POST)
    public
    @ResponseBody
    String handleImport(
            @RequestParam(value = "file", required = false) MultipartFile file,
            HttpServletResponse response) throws IOException {

        String uploadHome = GlobalVariable.getUploadHome();
        FileModel fileModel = new FileModel();

        if (file != null && StringUtils.hasText(file.getOriginalFilename())) {
//            System.out.println(file.getOriginalFilename());


            fileModel.setName(file.getOriginalFilename());
            fileModel.setSize(file.getSize());
            fileModel.setType(file.getContentType());
            String path = uploadService.saveFileToServer(file, uploadHome);
            fileModel.setPath(path);
        }

        uploadService.json_encode(response, fileModel);
        return null;

    }

    /**
     * 描述 : <事先就并不知道确切的上传文件数目,比如FancyUpload这样的多附件上传组件>. <br>
     *<p>

     * @param model
     * @param multipartRequest
     * @return
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    @RequestMapping(value = "/upload.multi", method = RequestMethod.POST)
    public 
    @ResponseBody
    String handleImport(
            DefaultMultipartHttpServletRequest multipartRequest,
            HttpServletResponse response) throws IOException {

        String uploadHome = GlobalVariable.getUploadHome();
        List<FileModel> list = new ArrayList<FileModel>();
        if (multipartRequest != null) {
            Iterator iterator = multipartRequest.getFileNames();

            while (iterator.hasNext()) {
                MultipartFile multifile =
                        multipartRequest.getFile((String) iterator.next());

                if (StringUtils.hasText(multifile.getOriginalFilename())) {
//                    System.out.println(multifile.getOriginalFilename());
                    FileModel fileModel = new FileModel();
                    fileModel.setName(multifile.getOriginalFilename());
                    fileModel.setSize(multifile.getSize());
                    String path = uploadService.saveFileToServer(multifile, uploadHome);
                    fileModel.setPath(path);
                    list.add(fileModel);
                }

            }
        }
        uploadService.json_encode(response, list);
        return null;

    }

    @RequestMapping(value = "/upload.*", method = RequestMethod.DELETE)
    public @ResponseBody String handleDelete(@RequestParam(value = "file", required = false) String file,
            HttpServletResponse response) throws IOException {
        String uploadHome = GlobalVariable.getUploadHome();
        boolean success = uploadService.deleteFiletoServer(file, uploadHome);
        uploadService.json_encode(response, success);
        return null;
    }
}


Service:
package com.swind.web.service;

import com.google.gson.Gson;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

@Service("uploadService")
public class UploadService {

    /**
     * 描述 : <将文件保存到指定路径>. <br>
     *<p>
     *
     * @param multifile
     * @param path
     * @return
     * @throws IOException
     */
    public String saveFileToServer(MultipartFile multifile, String path)
            throws IOException {
        // 创建目录
        File dir = new File(path);
        if (!dir.exists()) {
            dir.mkdir();
        }
        // 读取文件流并保持在指定路径
        InputStream inputStream = multifile.getInputStream();
        OutputStream outputStream = new FileOutputStream(path
                + multifile.getOriginalFilename());
        byte[] buffer = multifile.getBytes();
        int bytesum = 0;
        int byteread = 0;
        while ((byteread = inputStream.read(buffer)) != -1) {
            bytesum += byteread;
            outputStream.write(buffer, 0, byteread);
            outputStream.flush();
        }
        outputStream.close();
        inputStream.close();

        return path + multifile.getOriginalFilename();
    }
    public boolean deleteFiletoServer(String file, String path)
            throws IOException {
        boolean success = Boolean.FALSE;
        File f = new File(path+file);
        if (f.exists()) {
           f.delete();
           success = Boolean.TRUE;
        }


        return success;
    }
    public void json_encode(final HttpServletResponse response, Object o) throws IOException{
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        Gson gs = new Gson();
        out.write(gs.toJson(o));
    }
}


Bean:
package com.swind.web.model;

import java.io.Serializable;

public class FileModel implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 7964950152782381235L;
    private String name;
    private long size;
    private String path;
    private String type;

    /**
     * @return the path
     */
    public String getPath() {
        return path;
    }

    /**
     * @param path the path to set
     */
    public void setPath(String path) {
        this.path = path;
    }

    /**
     * @return the name
     */
    public String getName() {
        return name;
    }

    /**
     * @param name the name to set
     */
    public void setName(String name) {
        this.name = name;
    }

    /**
     * @return the size
     */
    public long getSize() {
        return size;
    }

    /**
     * @param size the size to set
     */
    public void setSize(long size) {
        this.size = size;
    }

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    
}


HTML UPload Page:
<!DOCTYPE HTML>
<!--
/*
 * jQuery File Upload Plugin HTML Example 4.1.2
 * https://github.com/blueimp/jQuery-File-Upload
 *
 * Copyright 2010, Sebastian Tschan
 * https://blueimp.net
 *
 * Licensed under the MIT license:
 * http://creativecommons.org/licenses/MIT/
 */
-->
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<title>jQuery File Upload Example</title>

<link rel="stylesheet" href="../res/css/themes/redmond/jquery-ui-1.8.1.custom.css" id="theme">
<link rel="stylesheet" href="../res/css/jquery.fileupload-ui.css">
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="file_upload">
    <form action="/GuzzProject/upload.multi" method="POST" enctype="multipart/form-data">
        <input type="file" name="file" multiple>
        <button type="submit">Upload</button>
        <div class="file_upload_label">上传文件</div>
    </form>
    <table class="files">
        <tr class="file_upload_template" style="display:none;">
            <td class="file_upload_preview"></td>
            <td class="file_name"></td>
            <td class="file_size"></td>
            <td class="file_upload_progress"><div></div></td>
            <td class="file_upload_start"><button>开始</button></td>
            <td class="file_upload_cancel"><button>取消</button></td>
        </tr>
        <tr class="file_download_template" style="display:none;">
            <td class="file_download_preview"></td>
            <td class="file_name"><a></a></td>
            <td class="file_size"></td>
            <td class="file_download_delete" colspan="3"><button>删除</button></td>
        </tr>
    </table>
    <div class="file_upload_overall_progress"><div style="display:none;"></div></div>
    <div class="file_upload_buttons">
        <button class="file_upload_start">全部开始</button>
        <button class="file_upload_cancel">全部结束</button>
        <button class="file_download_delete">全部删除</button>
    </div>
</div>
<script src="../res/js/jquery-core/jquery-1.5.2.min.js"></script>
<script src="../res/js/jquery-ui/jquery-ui-1.8.1.custom.min.js"></script>
<script src="../res/js/plugin/uploader/jquery.fileupload.js"></script>
<script src="../res/js/plugin/uploader/jquery.fileupload-ui.js"></script>
<script src="../res/js/plugin/uploader/jquery.fileupload-uix.js"></script>
<script src="application.js"></script>
</body> 
</html>


效果:
Spring MultipartFile 文件上传【注解】& JQuery uploader plugin_第1张图片


提供了静太部分的源文件下载,服务端的请自己写吧。


你可能感兴趣的:(java,spring,jquery,Web,json)