文件上传下载
程序员文章站
2022-07-13 12:46:19
...
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.upload.FormFile;
public class FileUpDownloader {
public static void uploadFile(FormFile file, String filePath) {
InputStream in = null;
OutputStream out = null;
try {
in = file.getInputStream();
out = new FileOutputStream(filePath);
int readed = 0;
byte[] buffer = new byte[1024];
while ((readed = in.read(buffer, 0, 1024)) != -1) {
out.write(buffer, 0, readed);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void downloadFile(HttpServletResponse response,String filePath) {
InputStream in = null;
OutputStream out = null;
BufferedInputStream bin = null;
BufferedOutputStream bout = null;
try {
File file = new File(filePath);
if (file.exists()) {
in = new FileInputStream(file);
bin = new BufferedInputStream(in);
out = response.getOutputStream();
bout = new BufferedOutputStream(out);
response.setHeader("Content-disposition","attachment;filename="+ URLEncoder.encode(filePath, "utf-8"));
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = bin.read(buffer, 0, 8192)) != -1) {
bout.write(buffer, 0, bytesRead);
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try{
bout.flush();
in.close();
bin.close();
out.close();
bout.close();
}catch(IOException e){
e.printStackTrace();
}
}
}
}
上一篇: jquery页面加载与javascript页面加载的区别
下一篇: web上传下载