Spring实践--SpringMVC文件操作-ResponseEntity

常用的ResponseEntity.BodyBuilder和自定义ResponseEntity例子

 

ResponseEntity.ok() 和 ResponseEntity.BodyBuilder() 
返回200(HttpStatus.SC_OK)

@RequestMapping("/check")
public ResponseEntity<String> check() {
    BodyBuilder builder = (BodyBuilder) ResponseEntity.ok();
    builder.allow(HttpMethod.GET);
    builder.contentType(MediaType.TEXT_HTML);
    builder.eTag("W/MyeTag\"");
    return builder.body("Hello World!");
}

ResponseEntity.status() 
使用HttpStatus返回需要的HttpCode

@RequestMapping("/handle")
public ResponseEntity<String> handle() {
   return ResponseEntity.status(HttpStatus.SC_CREATED).body("Created Success");
}

ResponseEntity.created() 
返回201(HttpStatus.SC_CREATED)

@RequestMapping("/handle")
public ResponseEntity<Void> handle() {
    URI location = null;
    try {
    location = new URI("http://www.concretepage.com/");
    } catch (URISyntaxException e) {
    e.printStackTrace();
    }
    return ResponseEntity.created(location).build();
} 

ResponseEntity.accepted() 
返回202(HttpStatus.SC_ACCEPTED)

@RequestMapping("/handle")
public ResponseEntity<String> handle() {
     return ResponseEntity.accepted().body("Hello World!");
} 

ResponseEntity.noContent() 
返回204(HttpStatus.SC_NO_CONTENT)

@RequestMapping("/handle")
public ResponseEntity<Void> handle() {
    return ResponseEntity.noContent().build();
} 

ResponseEntity.badRequest() 
返回400(HttpStatus.SC_BAD_REQUEST)

@RequestMapping("/handle")
public ResponseEntity<String> handle() {
   return ResponseEntity.badRequest().body("Bad Request");
} 

ResponseEntity.notFound() 
返回404(HttpStatus.SC_NOT_FOUND)

@RequestMapping("/handle")
public ResponseEntity<Void> handle() {
    return ResponseEntity.notFound().build();
} 

 使用实例:

pom.xml

<dependency>
	<groupId>commons-io</groupId>
	<artifactId>commons-io</artifactId>
	<version>2.4</version>
</dependency>

FileController.java

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller
@RequestMapping(value = "/file")
public class FileController {
	private static final Logger logger = LoggerFactory.getLogger(FileController.class);
	@Value("${spring.http.multipart.location}")
	private String uploadPath;

	@RequestMapping(value = "upload")
	@ResponseBody
	public String upload(@RequestParam("roncooFile") MultipartFile file) {
		if (file.isEmpty()) {
			return "文件为空";
		}

		// 获取文件名
		String fileName = file.getOriginalFilename();
		logger.info("上传的文件名为:" + fileName);

		// 获取文件的后缀名
		// String suffixName = fileName.substring(fileName.lastIndexOf("."));
		// logger.info("上传的后缀名为:" + suffixName);
		// 解决中文问题,liunx下中文路径,图片显示问题
		// fileName = UUID.randomUUID() + suffixName;

		File dest = new File(uploadPath + "/" + fileName);

		// 检测是否存在目录
		if (!dest.getParentFile().exists()) {
			dest.getParentFile().mkdirs();
		} else if (dest.exists()) {
			return "文件已经存在!";
		}

		try {
			file.transferTo(dest);
			return "上传成功";
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return "上传失败";
	}

	@RequestMapping("download")
	public ResponseEntity<?> download(String filepath) throws IOException, URISyntaxException {
		File file = new File(filepath);
		HttpHeaders headers = new HttpHeaders();
		if (!file.exists()) {
			URI location = new URI(filepath);
			HttpHeaders responseHeaders = new HttpHeaders();
			responseHeaders.setLocation(location);
			responseHeaders.set("MyResponseHeader", "MyValue");
			return new ResponseEntity<String>("文件路径不正确!", responseHeaders, HttpStatus.NOT_FOUND);
			// return ResponseEntity.noContent().build();
			// return ResponseEntity.notFound().build();
		}
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", file.getName());
		byte[] bytes = FileUtils.readFileToByteArray(file);
		return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);

	}
}

 

 

 

转载于:https://my.oschina.net/spinachgit/blog/1583068

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值