ssm upload image file to ftp (image compression processing)

Keywords: ftp Java JSON Apache

ssm upload image file to ftp (image compression processing)

Development tool Eclipse

1. Introduce jar package

Download address of jar package: Ali central warehouse

2. Configure spring-mvc.xml and add the following code

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">    
            <property name="defaultEncoding" value="utf-8"</property>
        <!-- Upload image maximum size 5 M=5242440 , 10MB=10*1024*1024=10485760 Byte 20=20971520-->     
        <property name="maxUploadSize" value="20971520"></property>    
</bean>

3. Add the upload file tool class ftutil.java

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

/**
 * Upload file tool class
 * 
 * 2017-12-23
 * @author Liner
 *
 */
public class FtpUtil {

    private static FTPClient ftpClient = new FTPClient();
    private static String encoding = System.getProperty("file.encoding");

    /**
     * Description: Upload files to FTP server
     * 
     * @Version1.0
     * 
     * @param url
     *            FTP Server hostname
     * @param port
     *            FTP Server port
     * @param username
     *            FTP Login account
     * @param password
     *            FTP Login password
     * @param path
     *            FTP The server saves the directory, or "/" if it is the root directory
     * 
     * @param  base64  Array, image data format returned by foreground
     * 
     * @return Back to server access link
     */
    public static  List<String> uploadBase64(String url, int port, String username, String password, String path, String[] base64_files) {
        List<String>  savelist=new ArrayList<>();

        try {
            int reply;
            // If you use the default port, you can use ftp.connect(url) to directly connect to the FTP server
            ftpClient.connect(url);
            // ftp.connect(url, port); / / connect to FTP server
            // Sign in
            ftpClient.login(username, password);
            ftpClient.setControlEncoding(encoding);
            // Verify successful connection
            reply = ftpClient.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                System.out.println("connection failed");
                ftpClient.disconnect();
                return savelist;
            }
            // Determine whether the folder already exists. If it does not exist, create it
            boolean isExit = ftpClient.makeDirectory(path);
            if (isExit) {
                System.out.println("Folder created successfully");
            } else {
                System.out.println("Folder already exists");
            }
            // Transfer working directory to specified directory
            boolean change = ftpClient.changeWorkingDirectory(path);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            if (change) {

                MultipartFile file;
                for (String base64 : base64_files) {

                    if (!base64.isEmpty()) {

                        //Parsing base64
                        byte[] b = Base64.decodeBase64(base64);
                        for (int i = 0; i < b.length; ++i) {
                            if (b[i] < 0) {// Adjust abnormal data
                                b[i] += 256;
                            }
                        }
                        //File name
                        String fileName = String.valueOf(System.currentTimeMillis())+".jpg";// File name such as a.jpg
                        file=new MockMultipartFile(fileName, b);//Convert to file
                        System.out.println("File name:" + fileName);

                        // Custom file name
                        // System.out.println("execute upload method! "";
                        Boolean bool = ftpClient.storeFile(new String(fileName.getBytes(encoding), "iso-8859-1"),file.getInputStream() );
                        if (bool) {
                            System.out.println("ok!");
                            // Access links, save to database
                            String savePath = WeiXinConfig.FTP_HOST + ":" + WeiXinConfig.FTP_PORT + path
                                    + File.separator + fileName;
                            System.out.println(savePath);
                            savelist.add(savePath);
                        }
                    }
                }

            }
            ftpClient.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftpClient.isConnected()) {
                try {
                    ftpClient.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return savelist;
    }
}

4.Action response code

    /**
     *  Upload pictures (multiple files)
     *  Liner 2017-12-19
     * @param files
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/uploadImagesBase", produces = "application/json; charset=UTF-8")
    public Object uploadImagesBase(@RequestParam("files") String[] files, HttpServletRequest request,HttpServletResponse response) throws Exception {

        //@RequestParam("files") MultipartFile[] files,
        //System.out.println("ready to upload! "";
        JSONObject json=new JSONObject();
        for(int i=0;i<files.length;i++){
            System.out.println(files[i]);
        }
        String msg="";
        if(files.length>0){
            String path = File.separator + TimeUtil.getShortDateString();

            // Call upload file interface
            List<String> savePath=FtpUtil.uploadBase64(WeiXinConfig.FTP_HOST, WeiXinConfig.FTP_PORT,
                            WeiXinConfig.FTP_USER_NAME, WeiXinConfig.FTP_PASSWORD, WeiXinConfig.FTP_BASEPATH + path,files);
            json.accumulate("savepath", savePath);

            if(savePath.size()>0){
                 msg="ok";
            }else{
                 msg="error";
            }

        }else{

            msg="files is null";
        }
        json.accumulate("msg", msg);

        return JSONSerializer.toJSON(json);
    }

5. Page code (partial code reference)

Reference link:[ https://www.cnblogs.com/guandekuan/p/6739190.html]

(1) . select File listening

//Select File listening event (single)
            $("#selectfile").change(function(e) {

                var files = e.target.files || e.dataTransfer.files;
                //console.log(files);

                var file = files[0];
                var reader = new FileReader();
                reader.readAsDataURL(file);
                reader.onload = function(e) {
                    var fileName = file.name; //file name
                    //var src = this.result;//

                    //var index = fileName.lastIndexOf(".");
                    //var filefix = fileName.substring(index, fileName.length); / / filename extension
                    msgShow('Picture processing,One moment please...');
                    lrz(file, {
                            width: 640
                        })
                        .then(function(rst) {
                            console.log(rst);
                            //Calculate file size
                            //var size=Math.round(rst.fileLen/1024*100)/100;
                            //console.log(size);
                            img_count++;
                            count++;
                            var img_id = 'img' + count; //Picture display ID
                            var file_id = 'file' + count; //File ID
                            imagesList.push(file_id); //Save ID to array
                            var base = rst.base64; //base64 string
                            //rename file

                            console.log(file);
                            file_map.put(file_id, base.split(',')[1]); //Save to file collection

                            var html = '<span class="img-item" id=' + img_id + ' >' + '<img src=' + base + ' />' +
                                '<a class="img-delete" href="javascript:;" onclick="delImg(' + count + ')"><span class="mui-icon mui-icon-closeempty"></span></a></span>';
                            $("#image-list").append(html); //Append display picture preview

                        }).always(function() {
                            //Whether compression is successful or not, execute  
                        });
                }
                $('#selectfile').val(''); //initialization
            });

(2) . upload file code

        //Submit (upload file method)
        function release() {


            //Determine whether to upload pictures
            if(imagesList.length>0){
                //Load animation
                layer.open({
                    type: 2,
                    shadeClose: false,
                    content: 'Uploading file to server, please wait...',
                });

                var url = "${ctx}/uploadImagesBase.do";
                var formData = new FormData(); // Instantiate upload method
                var file;
                //Add base64 format file to formData
                for(var i = 0; i < imagesList.length; i++) {
                    file = file_map.get(imagesList[i]);
                    formData.append("files", file);
                }

                var xhr = new XMLHttpRequest();
                xhr.upload.addEventListener("progress", uploadProgress, false);
                xhr.addEventListener("load", uploadComplete, false);
                xhr.addEventListener("error", uploadFailed, false);
                xhr.addEventListener("abort", uploadCanceled, false);
                xhr.open("POST", url,true);//In post mode, url is the server request address, and true specifies whether the request is processed asynchronously.
                xhr.send(formData); //Start uploading, send form data 
            }else{
                //No pictures need to be uploaded, submit directly
                submit();//Submission
            }
        }

        // Start upload
        function uploadProgress(evt) {
            // No processing

        }
        // Upload completion method
        function uploadComplete(evt) {

            console.log(evt);
            var data = JSON.parse(evt.target.responseText);
            if(data.msg == 'ok') {
                //Get return path
                layer.closeAll();
                saveList=data.savepath;
                console.log(saveList);
                if(saveList.length==img_count){
                    //msgShow("upload succeeded! "";
                    submit();//Submission

                }else{
                    msgShow("Some pictures failed to upload, please check the network!");
                }
            } else {
                layer.closeAll();
                msgShow("Upload failed!");
            }
        }
        // Upload error method
        function uploadFailed(evt) {
            // Popup 
            msgShow('Image upload failed!');

        }
        //
        function uploadCanceled(evt) {
            //Popup 
            msgShow('Picture upload has been canceled by user or browser!');
        }
        function msgShow(msg){
            //Tips
            layer.open({
                content: msg,
                skin: 'msg',
                time: 2 //Turn off automatically in 2 seconds
            });
        }

6. Problems needing attention
Question 1: http://blog.csdn.net/lingirl/article/details/1714806
Problem 2: after the compressed base is submitted to file file, IOS will fail to submit

Posted by asy1mpo on Mon, 04 May 2020 04:28:17 -0700