文章目录
- 1. 上传文件
- 1.1 单文件上传
- 1.2 单文件html代码
- 1.3 多文件上传
- 1.4 多文件html代码
- 文件上传带参数
- 2. 下载文件
- 3. 文件转文件16进制字符串
- 4. 文件16进制字符串转文件
- 5. 文件16进制字符串转文件输入流
- 6. 工具类方法
- 7. 上传文件大小限制配置
- 报错
- 文件过大问题
- 解决方案
1. 上传文件
1.1 单文件上传
@RequestMapping(value = "upload", method = RequestMethod.POST)
@ResponseBody
public String upload(MultipartFile excel) throws IOException {
// ...
return "success";
}
注意接口 upload 的参数名称是excel, 在 调用时文件的 key 也得是 excel
1.2 单文件html代码
<form action="XXXXXX" enctype="multipart/form-data" method="post">
<input type="file" name="excel" />
<br/>
<input type="submit" value="上传文件" />
</form>
1.3 多文件上传
@RequestMapping(value = "multiUpload", method = RequestMethod.POST)
@ResponseBody
public String multiUpload(@RequestParam("file") MultipartFile[] files) {
String[] fileNames = new String[files.length];
for (int i = 0; i < files.length; i++) {
MultipartFile file = files[i];
if (!file.isEmpty()) {
fileNames[i] = file.getOriginalFilename();
}
}
// ...
return Arrays.asList(fileNames).toString();
}
1.4 多文件html代码
<form action="XXXXXX" enctype="multipart/form-data" method="post">
文件1: <input type="file" name="file" />
<br/>
文件2: <input type="file" name="file" />
<br/>
<input type="submit" value="上传所有文件" />
</form>
文件上传带参数
@RequestMapping("/upload")
public Response upload(@RequestParam MultipartFile file,
@RequestParam("id") String id, @RequestParam String userName) {
// ...
return Response.success(id + "=" + userName);
}
2. 下载文件
@RequestMapping(value = "{fileName}")
public void download(@PathVariable("fileName") String fileName, HttpServletResponse response) {
// 根据 fileName 找到下载文件所在路径
String filePath = "/home/answer/" + fileName;
try {
File file = new File(filePath);
String filename = file.getName();
InputStream is = new BufferedInputStream(new FileInputStream(filePath));
byte[] buffer = new byte[is.available()];
is.read(buffer);
is.close();
response.reset();
response.setCharacterEncoding(Charsets.UTF_8.name());
response.addHeader("Content-Disposition", String.format("%s%s", "attachment;filename=", filename));
response.addHeader("Content-Length", String.valueOf(file.length()));
OutputStream os = new BufferedOutputStream(response.getOutputStream());
// application/octet-stream 不知道下载文件类型 application/x-xls
response.setContentType("application/vnd.ms-excel");
os.write(buffer);
os.flush();
os.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
3. 文件转文件16进制字符串
public class AIApp {
public static void main(String[] args) throws IOException {
BufferedInputStream bis = new BufferedInputStream(new FileInputStream("C:\\Users\\answer\\work_detail.txt"));
byte[] bytes = new byte[bis.available()];
bis.read(bytes, 0, bis.available());
System.out.println(bytesToHexString(bytes));
}
}
4. 文件16进制字符串转文件
public class AIApp {
public static void main(String[] args) throws IOException {
String fileHexString = "";
byte[] bytes = hexStringToBytes(fileHexString);
if (bytes != null) {
File file = new File("C:\\Users\\answer\\work.txt");
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
bos.write(bytes);
bos.flush();
bos.close();
}
}
}
5. 文件16进制字符串转文件输入流
/**
* 文件16进制字符串转文件流
*
* @param hexString 十六进制字符串
* */
public static InputStream hexToInputStream(String hexString) {
byte[] bytes = hexStringToBytes(hexString);
Assert.notNull(bytes, "bytes is null.");
return new ByteArrayInputStream(bytes);
}
6. 工具类方法
/**
* 十六进制字符串转字节数组
*
* @param hexString 十六进制字符串
* */
public static byte[] hexStringToBytes(String hexString) {
if (StringUtils.isEmpty(hexString)) {
return null;
}
hexString = hexString.toUpperCase();
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] d = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
}
return d;
}
/**
* 字符转字节
* */
public static byte charToByte(char c) {
return (byte) "0123456789ABCDEF".indexOf(c);
}
/**
* 字节数组转16进制字符串
*
* @param bytes 字节数组
* */
public static String bytesToHexString(byte[] bytes){
StringBuilder stringBuilder = new StringBuilder("");
if (bytes == null || bytes.length <= 0) {
return "";
}
for (byte b: bytes) {
int v = b & 0xFF;
String hv = Integer.toHexString(v);
if (hv.length() < 2) {
stringBuilder.append(0);
}
stringBuilder.append(hv);
}
return stringBuilder.toString().toUpperCase();
}
7. 上传文件大小限制配置
# 配置文件传输
# spring.servlet.multipart.enabled =true
# spring.servlet.multipart.file-size-threshold =0
# 单个数据的大小
spring.servlet.multipart.max-file-size=1024MB
# 总数据的大小
spring.servlet.multipart.max-request-size=1024MB
报错
文件过大问题
Maximum upload size exceeded; nested exception is java.lang.IllegalStateException: org.apache.tomcat.util.http.fileupload.FileUploadBase$SizeLimitExceededException: the request was rejected because its size (14809675) exceeds the configured maximum (10485760)
解决方案
解决方案1
# 解决方案: application.properties add
spring:
servlet:
multipart:
max-file-size: 1024MB
max-request-size: 1024MB
location: /home/jaemon/temp
解决方案2
@Configuration
public class MultipartConfig {
@Bean
public MultipartConfigElement multipartConfigElement() {
MultipartConfigFactory factory = new MultipartConfigFactory();
factory.setMaxFileSize("1024MB");
factory.setMaxRequestSize("1024MB");
// 上传文件临时目录
factory.setLocation("/home/jaemon/temp");
return factory.createMultipartConfig();
}
}