欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

SpringMVC 实现文件上传/下载

程序员文章站 2022-06-02 14:38:18
...

1. 上传文件

1.1 单文件上传

@RequestMapping(value = "upload", method = RequestMethod.POST)
@ResponseBody
public String upload(MultipartFile excel) throws IOException {
	// ...  
    return "success";
}

 
SpringMVC 实现文件上传/下载 

1.2 单文件html代码

<form action="XXXXXX" enctype="multipart/form-data" method="post">
    <input type="file" name="excel" />
        <br/>
    <input type="submit" value="上传文件" />
</form>

 

1.3 多文件上传

@RequestMapping(value = "multiUpload", method = RequestMethod.POST)
@ResponseBody
public String multiUpload(@RequestParam("file") MultipartFile[] files) {
    String[] fileNames = new String[files.length];
    for (int i = 0; i < files.length; i++) {
        MultipartFile file = files[i];
        if (!file.isEmpty()) {
            fileNames[i] = file.getOriginalFilename();
        }
    }
	// ...
    return Arrays.asList(fileNames).toString();
}

 
SpringMVC 实现文件上传/下载
 

1.4 多文件html代码

<form action="XXXXXX" enctype="multipart/form-data" method="post">
    文件1: <input type="file" name="file" />
    <br/>
    文件2: <input type="file" name="file" />
    <br/>
    <input type="submit" value="上传所有文件" />
</form>

 

2. 下载文件

@RequestMapping(value = "{fileName}")
public void download(@PathVariable("fileName") String fileName, HttpServletResponse response) {
    // 根据 fileName 找到下载文件所在路径
    String filePath = "/home/answer/" + fileName;
    try {
        File file = new File(filePath);
        String filename = file.getName();

        InputStream is = new BufferedInputStream(new FileInputStream(filePath));
        byte[] buffer = new byte[is.available()];
        is.read(buffer);
        is.close();

        response.reset();
        response.setCharacterEncoding(Charsets.UTF_8.name());
        response.addHeader("Content-Disposition", String.format("%s%s", "attachment;filename=", filename));
        response.addHeader("Content-Length", String.valueOf(file.length()));
        OutputStream os = new BufferedOutputStream(response.getOutputStream());
        // application/octet-stream 不知道下载文件类型 application/x-xls
        response.setContentType("application/vnd.ms-excel");
        os.write(buffer);
        os.flush();
        os.close();
    } catch (IOException ex) {
        ex.printStackTrace();
    }
}

 

3. 文件转文件16进制字符串

public class AIApp {
    public static void main(String[] args) throws IOException {
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\answer\\work_detail.txt"));
        byte[] bytes = new byte[bis.available()];
        bis.read(bytes, 0, bis.available());

        System.out.println(bytesToHexString(bytes));
    }
}

 

4. 文件16进制字符串转文件

public class AIApp {
    public static void main(String[] args) throws IOException {
        String fileHexString = "";
        byte[] bytes = hexStringToBytes(fileHexString);

        if (bytes != null) {
            File file = new File("C:\\Users\\answer\\work.txt");
            BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
            bos.write(bytes);
            bos.flush();
            bos.close();
        }
    }
}

 

5. 文件16进制字符串转文件输入流

/**
 * 文件16进制字符串转文件流
 *
 * @param hexString 十六进制字符串
 * */
public static InputStream hexToInputStream(String hexString) {
    byte[] bytes = hexStringToBytes(hexString);
    Assert.notNull(bytes, "bytes is null.");
    return new ByteArrayInputStream(bytes);
}

 

6. 工具类方法

/**
 * 十六进制字符串转字节数组
 *
 * @param  hexString 十六进制字符串
 * */
public static byte[] hexStringToBytes(String hexString) {
    if (StringUtils.isEmpty(hexString)) {
        return null;
    }
    hexString = hexString.toUpperCase();
    int length = hexString.length() / 2;
    char[] hexChars = hexString.toCharArray();
    byte[] d = new byte[length];
    for (int i = 0; i < length; i++) {
        int pos = i * 2;
        d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
    }
    return d;
}

/**
 * 字符转字节
 * */
public static byte charToByte(char c) {
    return (byte) "0123456789ABCDEF".indexOf(c);
}

/**
 * 字节数组转16进制字符串
 *
 * @param bytes 字节数组
 * */
public static String bytesToHexString(byte[] bytes){
    StringBuilder stringBuilder = new StringBuilder("");
    if (bytes == null || bytes.length <= 0) {
        return "";
    }

    for (byte b: bytes) {
        int v = b & 0xFF;
        String hv = Integer.toHexString(v);
        if (hv.length() < 2) {
            stringBuilder.append(0);
        }
        stringBuilder.append(hv);
    }
    return stringBuilder.toString().toUpperCase();
}