代码如下 :
import org.springframework.util.StringUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class UploadFile {
/*
文件下载
@param filepath 文件路径
*/
public static void uploadfile(HttpServletResponse response, String filepath) {
FileInputStream in = null;
ServletOutputStream op = null;
if (!StringUtils.isEmpty(filepath)) {
File file = new File(filepath);
if (file.exists()) {
response.reset(); // 重置
response.addHeader("Content-Length", "" + file.length());
response.addHeader("Content-Disposition", "attachment;filename=" + file.getName());
response.setHeader("content-type", "application/octet-stream");
response.setContentType("application/octet-stream");
try {
in = new FileInputStream(file);
op = response.getOutputStream();
int len = 0;
while ((len = in.read()) != -1) {
op.write(len);
}
op.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
ioclose(in, op);
}
}
}
}
public static void ioclose(InputStream inputStream, OutputStream outputStream) {
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}