import org
.springframework
.web
.bind
.annotation
.RequestMapping
;
import org
.springframework
.web
.bind
.annotation
.RequestParam
;
import org
.springframework
.web
.bind
.annotation
.RestController
;
import org
.springframework
.web
.multipart
.MultipartFile
;
import java
.io
.*
;
@RestController
public class UploadController {
@RequestMapping("upload")
public String
uploadFile(String params
, @RequestParam(name
= "file", required
= false) MultipartFile
[] file
) throws IOException
{
BufferedOutputStream out
= null
;
System
.out
.println("======接收报文:\n" + params
);
System
.out
.println("======文件数:\n" + file
.length
);
if (file
.length
> 0) {
try {
for (int i
= 0; i
< file
.length
; i
++) {
MultipartFile multipartFile
= file
[i
];
if (!multipartFile
.isEmpty()) {
System
.out
.println("fileName = [" + multipartFile
.getOriginalFilename() + "]");
out
= new BufferedOutputStream(
new FileOutputStream(new File(
multipartFile
.getOriginalFilename())));
out
.write(multipartFile
.getBytes());
out
.flush();
}
}
} catch (FileNotFoundException e
) {
e
.printStackTrace();
return "上传失败," + e
.getMessage();
} catch (IOException e
) {
e
.printStackTrace();
return "上传失败," + e
.getMessage();
} finally {
if (null
!= out
) {
out
.close();
}
}
} else {
System
.out
.println("==========没有文件=========");
}
return "上传成功";
}
@RequestMapping("upload1")
public String
uploadFile(String params
, @RequestParam(name
= "file", required
= false) MultipartFile file
) {
if (!params
.isEmpty()) {
System
.out
.println("======接收报文:\n" + params
);
} else {
return "上传失败,因为文件是空的.";
}
if (!file
.isEmpty()) {
try {
BufferedOutputStream out
=
new BufferedOutputStream(new FileOutputStream(new File(file
.getOriginalFilename())));
System
.out
.println(file
.getName());
out
.write(file
.getBytes());
out
.flush();
out
.close();
} catch (FileNotFoundException e
) {
e
.printStackTrace();
return "上传失败," + e
.getMessage();
} catch (IOException e
) {
e
.printStackTrace();
return "上传失败," + e
.getMessage();
}
return "上传成功";
} else {
return "上传失败,因为文件是空的.";
}
}
}
请求实例(或者调用代码进行上传,参考文章-字节流操作之文件上传客户端代码):
转载请注明原文地址: https://lol.8miu.com/read-3010.html