版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhaozhirongfree1111/article/details/84590947
- pom依赖
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
<spring.version>4.2.5.RELEASE</spring.version>
<slf4j.version>1.7.6</slf4j.version>
</properties>
<dependencies>
<!-- 文件上传相关JAR包 -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- LOG -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>${slf4j.version}</version>
</dependency>
</dependencies>
- controller
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
/**
* Created by zhaozhirong on 2018/11/27.
*/
@Controller
@RequestMapping("/file")
public class FileController {
private final Logger logger = LoggerFactory.getLogger(FileController.class);
@ResponseBody
@RequestMapping("upload")
public JsonResp uploadFile(
@RequestParam(value = "file", required = true) MultipartFile file
) {
JsonResp resp = new JsonResp();
File uploadFile = null;
InputStream is = null;
FileOutputStream fos = null;
try {
if (file.isEmpty()) {
resp.setRespInfo(JsonResp.FAIL, "Upload file can not be null or empty!");
return resp;
}
is = file.getInputStream();
File uploadDir = UploadUtil.getUploadDir();
uploadFile = new File(uploadDir, UUID.randomUUID().toString());
logger.debug("Upload file is: {}", uploadFile.getAbsolutePath());
fos = new FileOutputStream(uploadFile);
IOUtils.copy(is, fos);
fos.flush();
resp.setRespInfo(JsonResp.FAIL,"success");
resp.setResult(uploadDir.getAbsolutePath());
} catch (Exception e) {
logger.error(e.getMessage(), e);
resp.setRespInfo(JsonResp.FAIL, e.getMessage());
return resp;
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
resp.setRespInfo(JsonResp.FAIL, e.getMessage());
}
}
if (is != null) {
try {
is.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
resp.setRespInfo(JsonResp.FAIL, e.getMessage());
}
}
}
return resp;
}
@RequestMapping("/download")
public ResponseEntity<byte[]> export(String filePath) throws IOException {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
String fileName = filePath.substring(filePath.lastIndexOf(File.separator) + 1);
headers.setContentDispositionFormData("attachment", fileName);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(filePath)),
headers, HttpStatus.CREATED);
}
}
- 辅助类
/**
* Created by qiuyujiang on 2018/11/15.
*/
public class JsonResp {
public final static Integer SUCCESS = 0;
public final static Integer FAIL = 1;
private Integer code;
private String message;
private Object result;
public void setRespInfo(int code, String message) {
this.code = code;
this.message = message;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Object getResult() {
return result;
}
public void setResult(Object result) {
this.result = result;
}
}
- html
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/html">
<head>
<meta charset="UTF-8">
<link rel="icon" href="data:;base64,=">
<title></title>
</head>
<body>
<form id="file" enctype="multipart/form-data">
文件:<input type="file" name="file"/><input type="button" onclick="test('file');" value="上传"/>
</form>
</body>
</html>
<script src="/js/jquery-1.11.3.min.js"></script>
<script>
function test(formId) {
var formData = new FormData($('#'+formId)[0]);
$.ajax({
type: 'POST',
url: '/file/upload',
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(resp) {
console.log(resp);
}
});
}
</script>