You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
81 lines
2.8 KiB
Java
81 lines
2.8 KiB
Java
package com.glxp.api.util;
|
|
|
|
import org.apache.commons.fileupload.FileItem;
|
|
import org.apache.commons.fileupload.FileItemFactory;
|
|
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
|
|
import org.slf4j.Logger;
|
|
import org.slf4j.LoggerFactory;
|
|
import org.springframework.http.MediaType;
|
|
import org.springframework.web.multipart.MultipartFile;
|
|
import org.springframework.web.multipart.commons.CommonsMultipartFile;
|
|
|
|
import java.io.IOException;
|
|
import java.io.InputStream;
|
|
import java.io.OutputStream;
|
|
|
|
public class MultipartFileTest {
|
|
|
|
private static final Logger log = LoggerFactory.getLogger(MultipartFileTest.class);
|
|
|
|
private MultipartFileTest() { }
|
|
|
|
|
|
public static void main(String[] args) {
|
|
// 本地文件转为MultipartFile类型
|
|
String fileName="D:\\1s\\a6294b6b58de15136bb827dd1efdc76.jpg";
|
|
fileName = fileName.substring(fileName.lastIndexOf("/"));
|
|
}
|
|
|
|
public static MultipartFile getMultipartFile(InputStream inputStream, String fileName) {
|
|
FileItem fileItem = createFileItem(inputStream, fileName);
|
|
return new CommonsMultipartFile(fileItem);
|
|
}
|
|
|
|
|
|
public static MultipartFile[] getMultipartFiles(InputStream[] inputStream, String fileName) {
|
|
// 多文件转换
|
|
int length = inputStream.length;
|
|
MultipartFile[] multipartFiles = new MultipartFile[length];
|
|
for (int i = 0; i < length; i++) {
|
|
FileItem fileItem = createFileItem(inputStream[i], fileName);
|
|
multipartFiles[i] = new CommonsMultipartFile(fileItem);
|
|
}
|
|
return multipartFiles;
|
|
}
|
|
|
|
|
|
public static FileItem createFileItem(InputStream inputStream, String fileName) {
|
|
FileItemFactory factory = new DiskFileItemFactory(16, null);
|
|
FileItem fileItem = factory.createItem("file", MediaType.MULTIPART_FORM_DATA_VALUE, true, fileName);
|
|
int read = 0;
|
|
OutputStream os = null;
|
|
byte[] buffer = new byte[10 * 1024 * 1024];
|
|
try {
|
|
os = fileItem.getOutputStream();
|
|
while ((read = inputStream.read(buffer, 0, 4096)) != -1) {
|
|
os.write(buffer, 0, read);
|
|
}
|
|
inputStream.close();
|
|
} catch (IOException e) {
|
|
log.error("os write exception", e);
|
|
throw new IllegalArgumentException("文件流输出失败");
|
|
} finally {
|
|
if (os != null) {
|
|
try {
|
|
os.close();
|
|
} catch (IOException e) {
|
|
log.error("stream os close exception", e);
|
|
}
|
|
}
|
|
if (inputStream != null) {
|
|
try {
|
|
inputStream.close();
|
|
} catch (IOException e) {
|
|
log.error("stream inputStream close exception", e);
|
|
}
|
|
}
|
|
}
|
|
return fileItem;
|
|
}
|
|
}
|