使用ResponseEntity实现从服务器下载和向服务器上传文件功能

SpringMVC中使用ResponseEntity实现下载文件功能:

package com.atguigu.mvc.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 使用ResponseEntity实现下载文件功能
 *
 * @author ***
 * @create 2022-05-23 16:42
 */
@Controller
public class FileUpAndDownController {
    @RequestMapping("/testDown")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取服务器中文件的真实路径
        String realPath = servletContext.getRealPath("/static/img/图片1.png");
        //创建输入流
        InputStream is = new FileInputStream(realPath);
        //创建字节数组
        byte[] buffer = new byte[is.available()];
        //将流读到字节数组中
        is.read(buffer);
        //创建HttpHeaders对象设置响应头信息
        MultiValueMap<String,String> headers = new HttpHeaders();
        //设置要下载方式以及下载文件名字
        headers.add("Content-Disposition","attachment;filename=图片1.png");
        //设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        //创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(buffer,headers,statusCode);
        //关闭输入流
        is.close();
        return responseEntity;
    }
}

html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>测试文件上传下载</title>
</head>
<body>
<a th:href="@{/testDown}">下载图片1</a>
</body>
</html>

实现效果:

SpringMVC中使用ResponseEntity实现向服务器上传文件功能:

首先需要添加依赖:

<!--文件上传-->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.3.1</version>
    </dependency>

然后需要在SpringMVC配置文件中配置文件上传解析器,将上传的文件封装为MultipartFile对象

    <!--配置文件上传解析器,将上传的文件封装为MultipartFile-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"></bean>

html:

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>测试文件上传下载</title>
</head>
<body>
<a th:href="@{/testDown}">下载图片1</a>
<form th:action="@{/testUp}" method="post" enctype="multipart/form-data">
    头像:<input type="file" name="photo"><br>
    <input type="submit" value="上传">
</form>
</body>
</html>

控制器代码实现:

package com.atguigu.mvc.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 *
 * @author ***
 * @create 2022-05-23 16:42
 */
@Controller
public class FileUpAndDownController {  
    //使用ResponseEntity实现上传文件功能
    @RequestMapping("/testUp")
    public String testUp(MultipartFile photo,HttpSession session) throws IOException {
        String filename = photo.getOriginalFilename();
        ServletContext servletContext = session.getServletContext();
        String photoPath = servletContext.getRealPath("photo");
        File file = new File(photoPath);
        //判断photoPath所对应路径是否存在
        if (!file.exists()){
            //若不存在,则创建目录
            file.mkdir();
        }
        String finalPath = photoPath + File.separator + filename;
        photo.transferTo(new File(finalPath));
        return "success";
    }

}

实现效果

改进(将UUID和后缀名拼接后的结果作为最终文件名):

package com.atguigu.mvc.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 *
 * @author ***
 * @create 2022-05-23 16:42
 */
@Controller
public class FileUpAndDownController {
    //使用ResponseEntity实现下载文件功能
    @RequestMapping("/testDown")
    public ResponseEntity<byte[]> testResponseEntity(HttpSession session) throws IOException {
        //获取ServletContext对象
        ServletContext servletContext = session.getServletContext();
        //获取服务器中文件的真实路径
        String realPath = servletContext.getRealPath("/static/img/图片1.png");
        //创建输入流
        InputStream is = new FileInputStream(realPath);
        //创建字节数组
        byte[] buffer = new byte[is.available()];
        //将流读到字节数组中
        is.read(buffer);
        //创建HttpHeaders对象设置响应头信息
        MultiValueMap<String,String> headers = new HttpHeaders();
        //设置要下载方式以及下载文件名字
        headers.add("Content-Disposition","attachment;filename=图片1.png");
        //设置响应状态码
        HttpStatus statusCode = HttpStatus.OK;
        //创建ResponseEntity对象
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(buffer,headers,statusCode);
        //关闭输入流
        is.close();
        return responseEntity;
    }

    //使用ResponseEntity实现上传文件功能
    @RequestMapping("/testUp")
    public String testUp(MultipartFile photo,HttpSession session) throws IOException {
        String filename = photo.getOriginalFilename();
        //获取上传的文件的后缀名
        String suffixName = filename.substring(filename.lastIndexOf("."));
        //将UUID作为文件名
        String uuid = UUID.randomUUID().toString();
        //将UUID和后缀名拼接后的结果作为最终文件名
        filename = uuid + suffixName;
        //通过servletContext获取服务器中的poto目录的路径
        ServletContext servletContext = session.getServletContext();
        String photoPath = servletContext.getRealPath("photo");
        File file = new File(photoPath);
        //判断photoPath所对应路径是否存在
        if (!file.exists()){
            //若不存在,则创建目录
            file.mkdir();
        }
        String finalPath = photoPath + File.separator + filename;
        photo.transferTo(new File(finalPath));
        return "success";
    }

}

  • 2
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
Java可以使用以下两种方式实现服务器上传下载文件: 1. 使用FTP协议:FTP协议是一种文件传输协议,可以实现服务器上传下载文件Java中可以使用Apache Commons Net库来实现FTP文件传输。示例代码如下: ``` import org.apache.commons.net.ftp.*; public class FtpExample { public static void main(String[] args) { String server = "ftp.example.com"; int port = 21; String user = "username"; String pass = "password"; FTPClient client = new FTPClient(); try { client.connect(server, port); client.login(user, pass); client.enterLocalPassiveMode(); String remoteFile = "/path/to/remote/file"; File localFile = new File("/path/to/local/file"); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream(localFile)); boolean success = client.retrieveFile(remoteFile, outputStream); outputStream.close(); if (success) { System.out.println("File downloaded successfully."); } } catch (IOException e) { e.printStackTrace(); } finally { try { if (client.isConnected()) { client.logout(); client.disconnect(); } } catch (IOException e) { e.printStackTrace(); } } } } ``` 2. 使用HTTP协议:HTTP协议也可以用于文件传输,可以通过HTTP的POST和GET请求来实现文件上传和下载Java中可以使用Apache HttpClient库来实现HTTP文件传输。示例代码如下: ``` import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; public class HttpExample { public static void main(String[] args) { HttpClient httpClient = HttpClients.createDefault(); // 文件上传 HttpPost httpPost = new HttpPost("http://example.com/upload"); FileBody fileBody = new FileBody(new File("/path/to/local/file")); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.addPart("file", fileBody); httpPost.setEntity(builder.build()); try { HttpResponse response = httpClient.execute(httpPost); String result = EntityUtils.toString(response.getEntity()); System.out.println(result); } catch (IOException e) { e.printStackTrace(); } // 文件下载 HttpGet httpGet = new HttpGet("http://example.com/download?file=/path/to/remote/file"); try { HttpResponse response = httpClient.execute(httpGet); HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); OutputStream outputStream = new BufferedOutputStream(new FileOutputStream("/path/to/local/file")); byte[] buffer = new byte[1024]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, len); } outputStream.close(); inputStream.close(); EntityUtils.consume(entity); System.out.println("File downloaded successfully."); } } catch (IOException e) { e.printStackTrace(); } } } ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

hxung

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值