springmvc文件上传

11 篇文章 0 订阅
7 篇文章 0 订阅

SpringMVC文件上传的示例代码

1. 创建一个上传文件的HTML表单:
<form action="/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="Upload" />
</form>
2. 创建一个UploadController来处理文件上传请求:
@Controller
public class UploadController {
    @PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            return "redirect:/error";
        }
        
        try {
            // 获取文件名
            String fileName = file.getOriginalFilename();
            
            // 获取文件的字节数据
            byte[] bytes = file.getBytes();
            
            // 文件保存路径
            String filePath = "/path/to/save/" + fileName;
            
            // 将文件保存到指定路径
            Files.write(Paths.get(filePath), bytes);
            
            return "redirect:/success";
        } catch (IOException e) {
            e.printStackTrace();
            return "redirect:/error";
        }
    }
}
3. 创建一个DownloadController来处理文件下载请求:
@Controller
public class DownloadController {
    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile() {
        // 文件路径
        String filePath = "/path/to/file";
        
        // 创建文件对象
        File file = new File(filePath);
        
        // 创建文件资源对象
        Resource resource = new FileSystemResource(file);
        
        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + file.getName());
        
        return ResponseEntity.ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(resource);
    }
}
请注意,上述代码中的文件保存路径和下载文件路径需要根据实际情况进行修改

1. 导入依赖的包

在pom.xml文件中导入依赖的包:

<dependency>
  <groupId>commons-fileupload</groupId>
  <artifactId>commons-fileupload</artifactId>
  <version>1.3.3</version>
</dependency>

2. 配置文件上传解析器

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 必须和用户JSP 的pageEncoding属性一致,以便正确解析表单的内容 -->
        <property name="defaultEncoding" value="UTF-8"></property>
        <!-- 文件最大大小(字节) 1024*1024*50=50M-->
        <property name="maxUploadSize" value="52428800"></property>
        <!--resolveLazily属性启用是为了推迟文件解析,以便捕获文件大小异常-->
        <property name="resolveLazily" value="true"/>
  </bean>

3. 数据表

create table t_book_file
(
  file_id varchar(32) primary key comment '文件ID',
  real_name varchar(50) not null comment '文件名称',
  content_type varchar(50) not null comment '文件类型',
  url varchar(256) not null comment '文件路径'
);

在book表中加入一个字段来保存上传文件的ID,即:与file_id字段对应。

4. controller

在这里插入图片描述
编辑index.jsp
增加上传链接打开进入上传的页面
在这里插入图片描述
上传页面
在这里插入图片描述
该截图中的代码只是保存了图片,还需要将图片的信息保存到文件数据表中,请自行完善。

5. 下载

核心代码:

@RequestMapping(value="/download")
public ResponseEntity<byte[]> download(@RequestParam String fileId){

   //先根据文件id查询对应图片信息,相关的后台代码省略,自行编写
  
   //下载关键代码
   File file=new File(bookFile.getUrl());
   HttpHeaders headers = new HttpHeaders();//http头信息
   String downloadFileName = new String(fileName.getBytes("UTF-8"),"iso-8859-1");//设置编码
   headers.setContentDispositionFormData("attachment", downloadFileName);
   headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
   //MediaType:互联网媒介类型  contentType:具体请求中的媒体类型信息
   return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.OK);

}

下载功能链接,示例代码

<!-- 判断是否 存在图片,如果有图片则提供下载 -->
<c:if test="${not empty b.bookImages}">    
    <a href="${ctx}/bookFile/download?fileId=${b.bookImages}">下载图片</a>
</c:if>
  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

程序员不想YY啊

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

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

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

打赏作者

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

抵扣说明:

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

余额充值