1. 页面表单
<HTML>
<HEAD>
<TITLE>上传下载图片</TITLE>
<meta http-equiv="Content-Type" content="text/html; charset=GBK">
</head>
<body>
<form enctype="multipart/form-data" action="hello/fileUploadAction!fileUpload" method="post">
<table>
<tr>
<td>文件:</td>
<td><input type="file" name="uploadImage"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="upload">
<input type="reset" value="重 置">
</td>
</tr>
</table>
<img alt="qian" src="hello/fileUploadAction!fileDownload">
</form>
</body>
</html>
2. 上传下载实现
package action;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.UUID;
import org.apache.commons.io.FileUtils;
import base.BaseAction;
public class FileUploadAction extends BaseAction {
private static final long serialVersionUID = 1L;
private File uploadImage;
private String uploadImageFileName;
private String uploadImageContentType;
public File getUploadImage() {
return uploadImage;
}
public void setUploadImage(File uploadImage) {
this.uploadImage = uploadImage;
}
public String getUploadImageFileName() {
return uploadImageFileName;
}
public void setUploadImageFileName(String uploadImageFileName) {
this.uploadImageFileName = uploadImageFileName;
}
public String getUploadImageContentType() {
return uploadImageContentType;
}
public void setUploadImageContentType(String uploadImageContentType) {
this.uploadImageContentType = uploadImageContentType;
}
public String fileUpload() {
String path = "E:ssh\\struts2\\Struts_06\\fileDir";
File fileDir = new File(path);
if (!fileDir.exists()) {
fileDir.mkdirs();
}
int count = uploadImageFileName.lastIndexOf(".");
String ext = uploadImageFileName.substring(count);
UUID uuid = UUID.randomUUID();
String fileName = uuid + ext;
File file = new File(path + "\\" + fileName);
if (!file.exists()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
try {
FileUtils.copyFile(uploadImage, file);
} catch (IOException e) {
e.printStackTrace();
}
return "index";
}
public void fileDownload() {
File file = new File("E:ssh\\struts2\\Struts_06\\fileDir\\4fcd0f06-575a-47fc-a010-d0a232ef9947.jpg");
System.out.println(file);
resp.reset();
resp.setContentType("multipart/form-data");
resp.setHeader("Content-Disposition", "attachment;fileName="+file.getName());
InputStream in = null;
OutputStream out = null;
try {
in = new FileInputStream(file);
out = resp.getOutputStream();
byte[] b = new byte[(int)file.length()];
in.read(b);
out.write(b);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null)
out.close();
if (in != null)
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
String str = "fhh.jpg";
int i = str.lastIndexOf(".");
String string = str.substring(i);
System.out.println(string);
}
}