文件上传(记得关闭流)

时间:2021-11-13 02:19:24
form:

<basic name="smwd" label="导入" widget="FileUploader" referWidgets="param">
<value name="destform">fwglAdd</value>
<value name="action">upload</value>
<value name="fileTypes">*.doc;*.docx</value>
<value name="fileAmount">1</value>
</basic>
action:

try {
Map<String, File> l = (Map) bus.getValue("smwd");
if (l == null || l.isEmpty())
return;
for (String key : l.keySet()) {

System.out.println(" file name is: " + l.keySet());

File file = (File) l.get(key);
FileInputStream in = new FileInputStream(file);
String guid = java.util.UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
String d = System.getProperty("file.separator");//代表一个"/"
String path1 = String.valueOf(FileUpLoadAction.class.getResource(""));
System.out.println(path1.substring(6, path1.length()));
String os1 = System.getProperty("os.name");
if(os1.toLowerCase().startsWith("win")){//判断是不是windows操作系统
File writeFile = new File(path1.substring(6, path1.length()) + "upload" + d + guid + "_" + key);
FileOutputStream os = new FileOutputStream(writeFile);
byte[] b = new byte[1024];
int i = 0;
while ((i = in.read(b)) != -1) {
os.write(b, 0, i);
}
os.flush();//很重要
form.updateWidgetValue("path", writeFile);
form.updateWidgetValue("smwdmc", key);
in.close();//很重要
os.close();//很重要
}else{//如果是linux操作系统,路径前边要多加一个 "/"
File writeFile = new File(d+path1.substring(6, path1.length()) + "upload" + d + guid + "_" + key);
FileOutputStream os = new FileOutputStream(writeFile);
byte[] b = new byte[1024];
int i = 0;
while ((i = in.read(b)) != -1) {
os.write(b, 0, i);
}
os.flush();//很重要
form.updateWidgetValue("path", writeFile);
form.updateWidgetValue("smwdmc", key);
in.close();//很重要
os.close();//很重要
}


}

} catch (Exception e) {

e.printStackTrace();

}

相关文章