zimg icon indicating copy to clipboard operation
zimg copied to clipboard

dropzone.js+springmvc+apache httpclient4.5+zimg方案

Open longzhiyou opened this issue 9 years ago • 2 comments

前端代码


<!doctype html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <title>upload files</title>

    <link rel="stylesheet" href="dropzone.css">
    <!-- <link rel="stylesheet" href="style.css" /> -->
    <script src="dropzone.js"></script>

</head>
<body>




<form action="/file-upload"  id="my-awesome-dropzone" class="dropzone">
    <!--<div class="dropzone-previews"></div> &lt;!&ndash; this is were the previews should be shown. &ndash;&gt;-->

    <!-- Now setup your input fields -->
    <input type="text" name="username" />
    <input type="password" name="password" />

    <button type="submit">Submit data and files!</button>
</form>

<script type="text/javascript">
    Dropzone.options.myAwesomeDropzone = { // The camelized version of the ID of the form element

        //paramName: "userfile", // The name that will be used to transfer the file-
        // The configuration we've talked about above
        autoProcessQueue: false,
        uploadMultiple: true,
        parallelUploads: 100,
        maxFiles: 100,

        // The setting up of the dropzone
        init: function() {
            var  myDropzone = this;

            // First change the button to actually tell Dropzone to process the queue.
            this.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
                // Make sure that the form isn't actually being sent.
                e.preventDefault();
                e.stopPropagation();
                myDropzone.processQueue();
            });

            // Listen to the sendingmultiple event. In this case, it's the sendingmultiple event instead
            // of the sending event because uploadMultiple is set to true.
            this.on("sendingmultiple", function() {
                // Gets triggered when the form is actually being sent.
                // Hide the success button or the complete form.
            });
            this.on("successmultiple", function(files, response) {
                // Gets triggered when the files have successfully been sent.
                // Redirect user or notify of success.
            });
            this.on("errormultiple", function(files, response) {
                // Gets triggered when there was an error sending the files.
                // Maybe show form again, and notify user of error
            });
        }

    }
</script>
</body>

</html>



#### 后端代码

@Controller
public class FileUploadController {


    @RequestMapping(value="/file-upload", method=RequestMethod.POST)
    public @ResponseBody String handleFileUpload(MultipartHttpServletRequest request) throws IOException {


//        Map<String, String[]> parameterMap = request.getParameterMap();
//
        // 获取文件map
        Map<String, MultipartFile> filesMap = request.getFileMap();

        CloseableHttpClient httpclient = HttpClients.createDefault();




        try {
            HttpPost httppost = new HttpPost("http://192.168.1.14:4869/upload" );
//            HttpPost httppost = new HttpPost("http://demo.buaa.us/upload" );

//            httppost.setHeader("Content-Type", "jpg");
            httppost.addHeader("Content-Type", "jpeg");
//            httppost.addHeader("Content-Type", "image/jpeg");

            MultipartEntityBuilder builder = MultipartEntityBuilder.create();
//            builder.setMode(HttpMultipartMode.STRICT);

            for (Map.Entry<String, MultipartFile> entry  : filesMap.entrySet()) {
                String uploadedFile=entry.getKey();
                MultipartFile file = entry.getValue();

                String mimeType = file.getContentType();
                String filename = file.getOriginalFilename();
                byte[] bytes = file.getBytes();

//                BufferedOutputStream stream =
//                        new BufferedOutputStream(new FileOutputStream(new File(filename)));
//                stream.write(bytes);
//                stream.close();

                System.out.println("uploadedFileName:" + uploadedFile + "   fileName:" + filename + "  mimeType:" + mimeType);
                System.out.println("bytes:" + bytes.length);

//                builder.addBinaryBody(uploadedFile, bytes);

                ByteArrayEntity byteArrayEntity = new ByteArrayEntity(bytes);
                httppost.setEntity(byteArrayEntity);

            }



            System.out.println("executing request " + httppost.getRequestLine());

            Header[] headers =  httppost.getAllHeaders();
            CloseableHttpResponse response = httpclient.execute(httppost);
            try {
                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());
                HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                    System.out.println("Response content : " + EntityUtils.toString(resEntity));

                }
                EntityUtils.consume(resEntity);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                response.close();
            }
        } finally {
            httpclient.close();
        }




         return "You successfully uploaded !";

    }

后记

例子是传一张图片到zimg并返回json,如果用muliti form方式,看屏蔽的地方即可,如有问题请联系我.

longzhiyou avatar Sep 21 '15 12:09 longzhiyou

感谢分享!

buaazp avatar Sep 21 '15 15:09 buaazp

应该的,楼主大公无私,致敬。

longzhiyou avatar Sep 22 '15 01:09 longzhiyou