天天看点

通过Rest实现文件下载

在项目中需要对外提供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);
		}
	}
}
           

继续阅读