通过Rest实现文件下载

本文介绍了如何在项目中利用RESTful API设计实现文件下载功能,重点在于代码实现的关键点,帮助开发者理解如何构建这样的接口。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在项目中需要对外提供Rest风格的API实现文件的下载。现把实现的代码贴出来。关键的是要把

produces = MediaType.MULTIPART_FORM_DATA_VALUE才能实现下载。

import java.util.List;

import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.base.utils.FdfsUtils;
import com.business.model.FileInfo;

@RestController
@RequestMapping("/rest")
public class DownloadRestController {

	/**
	 * 下载
	 * 
	 * @param systemInfo
	 * @param ucBuilder
	 * @return
	 */
	@RequestMapping(value = "/download/", method = RequestMethod.POST, produces = MediaType.MULTIPART_FORM_DATA_VALUE)
	@Transactional
	public ResponseEntity<byte[]> downloadFile(@RequestBody FileInfo entity) {

		
		if (entity == null) {
			return new ResponseEntity<byte[]>(HttpStatus.BAD_REQUEST);
		} else {
			byte[] fileArray = FdfsUtils.downloadFromFdfs(entity.getFilePath());
			return new ResponseEntity<byte[]>(fileArray, HttpStatus.OK);
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值