Introduction of the Jersey


Jersey is an open source RESTful framework that implements the JAX-RS specification and provides more features and tools to further simplify RESTful service and client development, similar to Struts. It can also be integrated with Hibernate and Spring frameworks. It is used here to implement file upload functionality.

Introduction of depend on


Add Jersey-dependent dependencies to pom.xml

<dependency>
    <groupId>com.sun.jersey</groupId>
    <artifactId>jersey-client</artifactId>
    <version>1.18.1</version>
</dependency>
Copy the code

Then create a file utility class called FileUtils.

Generate temporary file method


/** * MultipartFile generates a temporary file *@param multipartFile
   * @paramTempFilePath tempFilePath *@returnFile Temporary File */
public static File multipartFileToFile(MultipartFile multipartFile, String tempFilePath) {

    File file = new File(tempFilePath);
    // Obtain the original name of the file
    String originalFilename = multipartFile.getOriginalFilename();
    // Get the file suffix
    String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
    if(! file.exists()) { file.mkdirs(); }// Create a temporary file
    File tempFile = new File(tempFilePath + "\ \" + UUID.randomUUID().toString().replaceAll("-"."") + suffix);
    try {
        if(! tempFile.exists()) {// Write to temporary filesmultipartFile.transferTo(tempFile); }}catch (IOException e) {
        e.printStackTrace();
    }
    return tempFile;
}
Copy the code

Method of encrypting/decrypting files


// The key to encrypt/decrypt the file
public static final int CRYPTO_SECRET_KEY = 0x99;

/** * Encrypt/decrypt files *@paramSrcFile Original file *@paramEncFile Encrypted/decrypted file *@returnEncrypted/decrypted file *@throws Exception
*/
public static File cryptoFile(File srcFile, File encFile) throws Exception {

    InputStream inputStream = new FileInputStream(srcFile);
    OutputStream outputStream = new FileOutputStream(encFile);
    while ((FILE_DATA = inputStream.read()) > -1) {
        outputStream.write(FILE_DATA ^ CRYPTO_SECRET_KEY);
    }
    inputStream.close();
    outputStream.flush();
    outputStream.close();
    return encFile;
}
Copy the code

Uploading files


/** * Upload file *@paramFileServerPath File server address *@paramFolderPath Path of the folder (for example, in the upload folder on the file server, that is, "/upload") *@paramUploadFile File to be uploaded *@paramIsCrypto Specifies whether to encrypt *@returnString Full path after the file is uploaded */
public static String uploadByJersey(String fileServerPath, String folderPath, File uploadFile, boolean isCrypto) {

    String suffix = uploadFile.getName().substring(uploadFile.getName().lastIndexOf("."));
    String randomFileName = UUID.randomUUID().toString().replaceAll("-"."") + suffix;
    String fullPath = fileServerPath + folderPath + "/" + randomFileName;
    try {
        if (isCrypto) {
            // Create the file to be uploaded
            File cryptoFile = new File(uploadFile.getPath().substring(0, uploadFile.getPath().lastIndexOf(".")) + "crypto" + uploadFile.getPath().substring(uploadFile.getPath().lastIndexOf(".")));
            // Perform encryption and overwrite the original file
            uploadFile = cryptoFile(uploadFile, cryptoFile);
        }
        // Create the Jersey server
        Client client = Client.create();
        WebResource wr = client.resource(fullPath);
        // Upload the file
        wr.put(String.class, fileToByte(uploadFile));
    } catch (Exception e) {
        e.printStackTrace();
    }
    return fullPath;
}
Copy the code

Download files


/** * Download file *@paramUrl File path *@paramFilePath File saving path *@paramFileName fileName (including file suffix) *@paramIsCrypto whether to decrypt *@return File
*/
public static File downloadByURL(String url, String filePath, String fileName, boolean isCrypto) {

    File file = new File(filePath);
    if(! file.exists()) { file.mkdirs(); } FileOutputStream fileOut; HttpURLConnection httpURLConnection; InputStream inputStream;try {
        URL httpUrl = new URL(url);
        httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
        httpURLConnection.setDoInput(true);
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setUseCaches(false);
        httpURLConnection.connect();
        inputStream = httpURLConnection.getInputStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
        if(! filePath.endsWith("\ \")) {
            filePath += "\ \";
        }
        file = new File(filePath + fileName);
        fileOut = new FileOutputStream(file);
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOut);
        byte[] bytes = new byte[4096];
        int length = bufferedInputStream.read(bytes);
        // Save the file
        while(length ! = -1) {
            bufferedOutputStream.write(bytes, 0, length);
            length = bufferedInputStream.read(bytes);
        }
        bufferedOutputStream.close();
        bufferedInputStream.close();
        httpURLConnection.disconnect();
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (isCrypto) {
        try {
            // Create the decrypted file
            File cryptoFile = new File(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext().getRealPath("/") +  "\\temp\\" + UUID.randomUUID().toString().replaceAll("-"."") + file.getName().substring(file.getName().lastIndexOf(".")));
            // Perform decryption
            cryptoFile(file, cryptoFile);
            // Delete the original downloaded file
            file.delete();
            // Save the decrypted file
            file = cryptoFile;
        } catch(Exception e) { e.printStackTrace(); }}return file;
}
Copy the code

Deleting files


/** * Delete files * from the file server@paramUrl File path *@return boolean
*/
public static boolean deleteByJersey(String url) {

    try {
        Client client = new Client();
        WebResource webResource = client.resource(url);
        webResource.delete();
        return true;
    } catch (UniformInterfaceException e) {
        e.printStackTrace();
    } catch (ClientHandlerException e) {
        e.printStackTrace();
    }
    return false;
}
Copy the code

Complete utility class


import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.UUID;

public class FileUtils {

    // The key to encrypt/decrypt the file
    public static final int CRYPTO_SECRET_KEY = 0x99;

    public static int FILE_DATA = 0;

    /** * Encrypt/decrypt files *@paramSrcFile Original file *@paramEncFile Encrypted/decrypted file *@throws Exception
     */
    public static void cryptoFile(File srcFile, File encFile) throws Exception {

        InputStream inputStream = new FileInputStream(srcFile);
        OutputStream outputStream = new FileOutputStream(encFile);
        while ((FILE_DATA = inputStream.read()) > -1) {
            outputStream.write(FILE_DATA ^ CRYPTO_SECRET_KEY);
        }
        inputStream.close();
        outputStream.flush();
        outputStream.close();
    }

    /** * MultipartFile generates a temporary file *@param multipartFile
     * @paramTempFilePath tempFilePath *@returnFile Temporary File */
    public static File multipartFileToFile(MultipartFile multipartFile, String tempFilePath) {

        File file = new File(tempFilePath);
        // Obtain the original name of the file
        String originalFilename = multipartFile.getOriginalFilename();
        // Get the file suffix
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        if(! file.exists()) { file.mkdirs(); }// Create a temporary file
        File tempFile = new File(tempFilePath + "\ \" + UUID.randomUUID().toString().replaceAll("-"."") + suffix);
        try {
            if(! tempFile.exists()) {// Write to temporary filesmultipartFile.transferTo(tempFile); }}catch (IOException e) {
            e.printStackTrace();
        }
        return tempFile;
    }

    /** * Upload file *@paramFileServerPath File server address *@paramFolderPath Path of the folder (for example, in the upload folder on the file server, that is, "/upload") *@paramUploadFile File to be uploaded *@paramIsCrypto Specifies whether to encrypt *@returnString Full path after the file is uploaded */
    public static String uploadByJersey(String fileServerPath, String folderPath, File uploadFile, boolean isCrypto) {

        String suffix = uploadFile.getName().substring(uploadFile.getName().lastIndexOf("."));
        String randomFileName = UUID.randomUUID().toString().replaceAll("-"."") + suffix;
        String fullPath = fileServerPath + folderPath + "/" + randomFileName;
        try {
            if (isCrypto) {
                // Create an encrypted file
                File cryptoFile = new File(uploadFile.getPath().substring(0, uploadFile.getPath().lastIndexOf(".")) + "crypto" + uploadFile.getPath().substring(uploadFile.getPath().lastIndexOf(".")));
                // Perform encryption
                cryptoFile(uploadFile, cryptoFile);
                // Save the encrypted file
                uploadFile = cryptoFile;
            }
            // Create the Jersey server
            Client client = Client.create();
            WebResource wr = client.resource(fullPath);
            // Upload the file
            wr.put(String.class, fileToByte(uploadFile));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return fullPath;
    }

    /** * Download file *@paramUrl File path *@paramFilePath File saving path *@paramFileName fileName (including file suffix) *@paramIsCrypto whether to decrypt *@return File
     */
    public static File downloadByURL(String url, String filePath, String fileName, boolean isCrypto) {

        File file = new File(filePath);
        if(! file.exists()) { file.mkdirs(); } FileOutputStream fileOut; HttpURLConnection httpURLConnection; InputStream inputStream;try {
            URL httpUrl = new URL(url);
            httpURLConnection = (HttpURLConnection) httpUrl.openConnection();
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setUseCaches(false);
            httpURLConnection.connect();
            inputStream = httpURLConnection.getInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            if(! filePath.endsWith("\ \")) {
                filePath += "\ \";
            }
            file = new File(filePath + fileName);
            fileOut = new FileOutputStream(file);
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOut);
            byte[] bytes = new byte[4096];
            int length = bufferedInputStream.read(bytes);
            // Save the file
            while(length ! = -1) {
                bufferedOutputStream.write(bytes, 0, length);
                length = bufferedInputStream.read(bytes);
            }
            bufferedOutputStream.close();
            bufferedInputStream.close();
            httpURLConnection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (isCrypto) {
            try {
                // Create the decrypted file
                File cryptoFile = new File(((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getServletContext().getRealPath("/") +  "\\temp\\" + UUID.randomUUID().toString().replaceAll("-"."") + file.getName().substring(file.getName().lastIndexOf(".")));
                // Perform decryption
                cryptoFile(file, cryptoFile);
                // Delete the original downloaded file
                file.delete();
                // Save the decrypted file
                file = cryptoFile;
            } catch(Exception e) { e.printStackTrace(); }}return file;
    }

    /** * Delete files * from the file server@paramUrl File path *@return boolean
     */
    public static boolean deleteByJersey(String url) {

        try {
            Client client = new Client();
            WebResource webResource = client.resource(url);
            webResource.delete();
            return true;
        } catch (UniformInterfaceException e) {
            e.printStackTrace();
        } catch (ClientHandlerException e) {
            e.printStackTrace();
        }
        return false;
    }

    /** * File Turn Bytes *@param file
     * @return byte[]
     */
    public static byte[] fileToByte(File file) {

        byte[] buffer = null;
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int n;
            while((n = fileInputStream.read(bytes)) ! = -1) {
                byteArrayOutputStream.write(bytes, 0, n);
            }
            fileInputStream.close();
            byteArrayOutputStream.close();
            buffer = byteArrayOutputStream.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        returnbuffer; }}Copy the code

Test the upload


/ * * *@paramMultipartFile Upload file *@paramIsCrypto Specifies whether to encrypt files *@return* /
@Test
public String upload(MultipartFile multipartFile, boolean isCrypto) {

    HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    // Generate temporary files
    File tempFile = FileUtil.multipartFileToFile(multipartFile, request.getServletContext().getRealPath("/") + "\\static\\temp");
    // Upload the file and return the file path
    String uploadFilePath = FileUtil.uploadByJersey("http://localhost:8080"."/upload", tempFile, isCrypto);
    if(uploadFilePath ! =null) {
        return "Upload successful";
    }
    else {
        return "Upload failed"; }}Copy the code

For more dry stuff, go to Antoniopeng.com

For more dry stuff, go to Antoniopeng.com