码迷,mamicode.com
首页 > 编程语言 > 详细

SpringMVC结合Ajaxfileupload异步多文件上传至远程服务器

时间:2014-12-29 12:21:16      阅读:415      评论:0      收藏:0      [点我收藏+]

标签:

<input type="file" id="playeraddress" name="playeraddress" />
<input type="file" id="cover" name="cover" />
//这里就是两个file id自己定义
$.ajaxFileUpload({
    url : web_path+‘upload/upload.do‘,
    secureuri : false,
    data : data,//需要传递的数据 json格式
    fileElementId :[‘playeraddress‘,‘cover‘],
    dataType : ‘json‘,
    success : function(data) {
           //上传成功后的回调。
    },
    error : function(data) {
    }
});
/**
     *
     * 
     * @param request
     * @param response
     * @param audioItem
     * @return
     */
    @RequestMapping(value = "/upload.do", method = { RequestMethod.POST })
    @ResponseBody
    public String addMusic(HttpServletRequest request,
            HttpServletResponse response, AudioItem audioItem) {
        //这里无需理会,这只是
        String uploadFileUrl = GlobalUtil .getValue("upload_audioItem_audio_url");
        String uploadIconUrl = GlobalUtil.getValue("upload_audioItem_pic_url");

        CommonsMultipartResolver resolver = new CommonsMultipartResolver(
                request.getServletContext());
        if (resolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while (iter.hasNext()) {
                String fileName = iter.next();
                // 取得上传文件
                MultipartFile file = multiRequest.getFile(fileName);
                /**
                 * 获取文件名
                 */
                String originalFilename = file.getOriginalFilename();
                
                if ("playeraddress".equals(fileName)&&!"".equals(originalFilename)) {
                    try {
                        //这里的upload方法就是以http post的方式上传文件的 稍后贴出
                        String url = BaseService.upload(uploadFileUrl,
                                file.getOriginalFilename(),
                                file.getInputStream());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
                if ("cover".equals(fileName)&&!"".equals(originalFilename)){
                    try {
                        String icon = BaseService.upload(uploadIconUrl,
                                file.getOriginalFilename(),
                                file.getInputStream());
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }
            //这里需要注意 使用Ajaxfileupload需要使用以下方式返回结果 回调不了success 方法
            response.setContentType("text/html");
  
            try {
                response.getWriter().write("ok");
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return null;
    }
//最后一步了 
    public static String upload(String httpurl, String fileName, InputStream inputStream) {
        String result = "";
        try {
            //这里看你的网络环境 按需设置代理  正常都不需要理会
            if (true) {
                System.setProperty("http.proxyHost", BaseService.PROXY_IP);
                System.setProperty("http.proxyPort", BaseService.PROXY_PORT);
            }
            String BOUNDARY = "---------7d4a6d158c9"; // 定义数据分隔线
            URL url = new URL(httpurl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setUseCaches(false);
            conn.setRequestMethod("POST");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)");
            conn.setRequestProperty("Charsert", "UTF-8");
            conn.setRequestProperty("Content-Type",
                    "multipart/form-data; boundary=" + BOUNDARY);
            OutputStream out = new DataOutputStream(conn.getOutputStream());
            byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
            StringBuilder sb = new StringBuilder();
            sb.append("--");
            sb.append(BOUNDARY);
            sb.append("\r\n");
            sb.append("Content-Disposition: form-data;name=\"file" + 1
                    + "\";filename=\"" + fileName + "\"\r\n");
            sb.append("Content-Type:application/octet-stream\r\n\r\n");
            byte[] data = sb.toString().getBytes();
            out.write(data);
            DataInputStream in = new DataInputStream(inputStream);
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            out.write("\r\n".getBytes()); // 多个文件时,二个文件之间加入这个
            in.close();
            out.write(end_data);
            out.flush();
            out.close();
            // 定义BufferedReader输入流来读取URL的响应
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    conn.getInputStream()));

            String line = null;
            while ((line = reader.readLine()) != null) {
                result+=line;
            }
        } catch (Exception e) {
            System.out.println("发送POST请求出现异常!" + e);
        }    
        return new JSONObject(result).getString("url");
    }
// 到这就结束了!希望能帮到你。


SpringMVC结合Ajaxfileupload异步多文件上传至远程服务器

标签:

原文地址:http://my.oschina.net/pingdy/blog/361833

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!