Java文件处理:form-data 文件上传和下载

pom.xml

		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.17</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.17</version>
		</dependency>

服务端代码

以下代码只代表实现方法、具体使用需要根据框架进行修改

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class FileServer {

    /**
     * 2003 excel后缀
     */
    private static final String EXCEL_XLS = "xls";

    /**
     * 2007 及以上版本excel后缀
     */
    private static final String EXCEL_XLSX = "xlsx";

    public String uploadFile(HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile file = multipartRequest.getFile("file");
        File desFile = new File("E:\\" + file.getOriginalFilename());
        if (!desFile.getParentFile().exists()) {
            desFile.mkdirs();
        }
        try {
            file.transferTo(desFile);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
            return "FAILED";
        }
        return "SUCCESS";
    }

    public String downloadFile(HttpServletResponse response) {
        OutputStream out = null;
        try {
            // 获取输入流
            File file = new File("E:\\123.txt");
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
            // 保持文件名
            String fileName = file.getName();
            // 防止中文名乱码
            fileName = URLEncoder.encode(fileName, "UTF-8");
            // 设置文件下载头
            response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
            // 设置文件ContentType类型
            response.setContentType("multipart/form-data");
            out = new BufferedOutputStream(response.getOutputStream());
            String suffix = StringUtils.substringAfterLast(fileName, ".");
            if ((suffix.equals(EXCEL_XLS) || suffix.equals(EXCEL_XLSX))) {
                Workbook workbook = WorkbookFactory.create(new FileInputStream(file));
                workbook.write(out);
                workbook.close();
            } else {
                byte[] buff = new byte[10 * 1024];
                while (in.read(buff) != -1) {
                    out.write(buff);
                    //清空缓存区中的数据流
                    out.flush();
                }
            }
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "SUCCESS";
    }

}
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java中可以使用HttpURLConnection来实现multipart/form-data POST上文件。下面是一个示例代码: ```java import java.io.File; import java.io.FileInputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; public class FileUploader { public static void main(String[] args) throws Exception { String apiUrl = "http://example.com/upload"; String filePath = "/path/to/file"; uploadFile(apiUrl, filePath); } public static void uploadFile(String apiUrl, String filePath) throws Exception { URL url = new URL(apiUrl); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setDoOutput(true); conn.setRequestMethod("POST"); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=boundary"); File file = new File(filePath); String fileName = file.getName(); FileInputStream inputStream = new FileInputStream(file); OutputStream outputStream = conn.getOutputStream(); outputStream.write(("--boundary\r\n" + "Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n").getBytes()); byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.write(("\r\n--boundary--").getBytes()); outputStream.flush(); outputStream.close(); int responseCode = conn.getResponseCode(); System.out.println("Response Code: " + responseCode); } } ``` 在示例代码中,首先指定了上文件的API地址和文件路径。然后通过HttpURLConnection打开连接,并设置请求方法为POST,Content-Type为multipart/form-data。接着读取文件内容,将文件内容写入请求的OutputStream中。最后获取响应码,如果响应码为200,则说明文件成功。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值