struts action 輸入流的方式:
public String savePictures() throws Exception {
String newFileName = null;
BufferedOutputStream bos = null;
BufferedInputStream bis = null;
String reInfo = "";// 上传成功返回的东西
for (int i = 0; i < pictureFile.size(); i++) {
long now = new Date().getTime();
int index = pictureFileFileName.get(i).lastIndexOf('.');
String path = ServletActionContext.getServletContext().getRealPath(
"a");
File dir = new File(path);
if (!dir.exists())
dir.mkdir();// 创建个文件夹
if (index != -1) {
newFileName = pictureFileFileName.get(i).substring(0, index)
+ "-" + now
+ pictureFileFileName.get(i).substring(index);// 生成新文件名
} else {
newFileName = pictureFileFileName.get(i) + "-" + now;
}
reInfo += newFileName + "@";
bos = null;
bis = null;
try {
FileInputStream fis = new FileInputStream(pictureFile.get(i)); // /
bis = new BufferedInputStream(fis);
FileOutputStream fos = new FileOutputStream(new File(dir,
newFileName));
bos = new BufferedOutputStream(fos);
byte[] buf = new byte[4096];
int len = -1;
while ((len = bis.read(buf)) != -1) {
bos.write(buf, 0, len);
}
} catch (Exception e) {
try {
String msg = "{success:false,errors:{name:'上传错误'}}";
response.getWriter().write(msg);
} catch (IOException e1) {
e1.printStackTrace();
}
} finally {
try {
if (null != bis)
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
if (null != bos)
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Cache", "no-cache");
PrintWriter out = null;
try {
out = response.getWriter();
out.write("{success:true}");
} catch (Exception e) {
Log4JFactory.instance().error(Util.SITE_LOG +" savePictures failed", e);
}finally {
if (out != null) {
out.close();
}
}
return SUCCESS;
}
或者是:包裝方法
public String uploadfiles() {
// 定义保存的路径
String savepath = getSavePath();
// 根据路径创建文件路径对象
File file = new File(savepath);
if (!file.exists()) {
file.mkdirs();
}
try {
for (int i = 0; i < pic.length; i++) {
FileUtils.copyFile(pic[i], new File(file, getPicFileName()[i]));
}
} catch (Exception ex) {
ex.printStackTrace();
}
return "SUCCESS";
}