[英]Converting java.io.File to org.apache.struts.upload.FormFile
I am in a situation where i have to cast a java.io.File
object to Struts org.apache.struts.upload.FormFile
object. 我处于必须将
java.io.File
对象org.apache.struts.upload.FormFile
为Struts org.apache.struts.upload.FormFile
对象的情况。 The type conversion is resulting in error. 类型转换导致错误。 Can any one suggest a way or a code snippet that i can use to do above operation.
任何人都可以提出一种我可以用来执行上述操作的方法或代码段吗? Any advice would be helpful.
任何意见将是有益的。
I implemented the above sugesstion and it worked for me. 我实施了上述建议,并且对我有用。 It dynamically converted a java File to a FormFile.
它动态地将Java文件转换为FormFile。 U also have to set the file name & size while converting it dynamically.
在动态转换文件时,U还必须设置文件名和大小。
public String getFileName() {
return this.file.getName();
}
public int getFileSize() {
return (int) this.file.length();
}
while invoking this wrapper this you have to pass the file location & can directly assign it to the FormFile. 在调用此包装器时,您必须传递文件位置,并且可以将其直接分配给FormFile。
FileWrapper fileWr = new FileWrapper(new File("X://file/file.xlsx"));
FormFile file = fileWr;
String fileName = file.getFileName();
You can't directly cast File to FormFile because File does't implement FormFile interface. 您不能直接将File转换为FormFile,因为File没有实现FormFile接口。 But you can create wrapper for File object and implement this interface.
但是您可以为File对象创建包装器并实现此接口。 Something like: import org.apache.struts.upload.FormFile;
类似于:import org.apache.struts.upload.FormFile;
import java.io.*;
public class FileWrapper implements FormFile {
private final File file;
public FileWrapper(File file) {
this.file = file;
}
@Override
public String getContentType() {
}
@Override
public void setContentType(String s) {
}
@Override
public int getFileSize() {
}
@Override
public void setFileSize(int i) {
}
@Override
public String getFileName() {
}
@Override
public void setFileName(String s) {
}
@Override
public byte[] getFileData() throws IOException {
byte[] buffer = new byte[(int) file.length()];
FileInputStream fileInputStream = new FileInputStream(file);
fileInputStream.read(buffer);
fileInputStream.close();
return buffer;
}
@Override
public InputStream getInputStream() throws IOException {
return new FileInputStream(file);
}
@Override
public void destroy() {
if (!file.delete()) {
throw new RuntimeException("File " + file.getName() + " can't be deleted");
}
}
}
Here I haven't implemented all methods because implementation depends on your requirements. 这里我没有实现所有方法,因为实现取决于您的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.