1.example(从程序写到本地)
String tempPath = "F:\\temp\\test\\test.txt";
//生成文件
try {
File files = new File(tempPath);
if(!files.exists()){
files.createNewFile();
}
String content = "key = value";
FileWriter fw = new FileWriter(files.getAbsoluteFile(),true);
BufferedWriter bw= new BufferedWriter(fw);
bw.write(content);
bw.flush();
bw.close();
fw.close();
}catch (IOException e){
}
2.example2(file 转成 MultipartFile )
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
(1) (file转成multifile)FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "textField";
int num = tempPath.lastIndexOf(".");
String extFile = tempPath.substring(num);
FileItem item = factory.createItem(textFieldName, "text/plain", true, "MyFileName");
File newfile = new File(tempPath);
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(newfile);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
MultipartFile mfile = new CommonsMultipartFile(item);
(2)(file转成multifile,并上传文件到oss)ResponseBean responseBean = new ResponseBean();
String fileName = "zh_CN.js";
String tempPath = this.getClass().getResource("").getPath()+"\\zh_CN.js";
MultipartFile multipartFile = null;
//上传文件
try {
File f = new File(tempPath);
FileItem fileItem = new DiskFileItem(fileName, Files.probeContentType(f.toPath()), false, f.getName(), (int) f.length(), f.getParentFile());
try (InputStream input = new FileInputStream(f); OutputStream os = fileItem.getOutputStream();) {
IOUtils.copy(input, os);
multipartFile = new CommonsMultipartFile(fileItem);
}
if (multipartFile != null) {
FileResult fileResult = fileUplaod.upload(multipartFile.getSize(), multipartFile.getContentType(), fileName, multipartFile.getInputStream());
System.out.println("fileResult: "+fileResult.toString() +" url: "+fileResult.getFileUrl()+" key: "+fileResult.getFileKey());
return responseBean.success(fileResult);
}
} catch (IOException e) {
logger.error("上传文件失败", e);
return responseBean.failure("文件上传失败");
}
return responseBean.success("true");
371

被折叠的 条评论
为什么被折叠?



