1、上传到disk
步骤:
//1、创建DiskFileItemFactory对象,设置缓冲区大小和临时文件目录。
new DiskFileItemFactory;
//2、使用DiskFileItemFactory 对象创建ServletFileUpload对象,并设置上传文件的大小限制。
new ServletFileUpload(diskFileItemFactory);
//3、调用ServletFileUpload.parseRequest方法解析request对象,得到一个保存了所有上传内容的List对象。
servletFileUpload.parseRequest(request);
//4、对list进行迭代,每迭代一个FileItem对象,调用其isFormField方法判断是否是上传文件:
for(FileItem fileItem : item){
if(fileItem.isFormFiled()){
}
//4.1为普通表单字段,则调用getFieldName、getString方法得到字段名和字段值。
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");
System.out.println(name+":"+value);
//4.2.为上传文件,则调用getInputStream方法得到数据输入流,从而读取上传数据
String fileName = fileItem.getName();
long size = fileItem.getSize();
System.out.println(fileName+":"+size+"Byte");
InputStream inputStream = fileItem.getInputStream();
String path =req.getServletContext().getRealPath("file/"+fileName);
OutputStream outputStream = new FileOutputStream(path);
int temp = 0;
while((temp = inputStream.read())!=-1){
outputStream.write(temp);
注意:
1、input 的 type 设置为 file,因为是针对文件的
2、form 表单的 method 设置 post,因为get 请求会将⽂件名传给服务端,⽽不是⽂件本身
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form enctype="multipart/form-data" action="/upload" method="post">
<input name="desc" type="text"/><br/>
<input name="text" type="file"/><br/>
<input type="submit" value="上传"/>
</form>
</body>
</html>
文件上传
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
try {
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
List<FileItem> list = servletFileUpload.parseRequest(req);
for(FileItem fileItem : list){
if(fileItem.isFormField()){
String name = fileItem.getFieldName();
String value = fileItem.getString("UTF-8");
System.out.println(name+":"+value);
}else{
String fileName = fileItem.getName();
long size = fileItem.getSize();
System.out.println(fileName+":"+size+"Byte");
InputStream inputStream = fileItem.getInputStream();
String path =req.getServletContext().getRealPath("file/"+fileName);
OutputStream outputStream = new FileOutputStream(path);
int temp = 0;
while((temp = inputStream.read())!=-1){
outputStream.write(temp);
}
outputStream.close();
inputStream.close();
System.out.println("上传成功");
}
}
} catch (FileUploadException e) {
e.printStackTrace();
}
}
}
文件下载
@WebServlet("/download")
public class DownloadServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
String type = req.getParameter("type");
String fileName = "";
switch (type){
case "png":
fileName = "1.png";
break;
case "txt":
fileName = "test.txt";
break;
}
resp.setContentType("application/x-msdownload");
resp.setHeader("Content-Disposition","attachment;filename="+fileName);
OutputStream outputStream = resp.getOutputStream();
String path = req.getServletContext().getRealPath("file/"+fileName);
InputStream inputStream = new FileInputStream(path);
int temp = 0;
while((temp=inputStream.read())!=-1){
outputStream.write(temp);
}
inputStream.close();
outputStream.close();
}
}
2、上传到ftp
private static boolean uploadFile2(String originFileName, InputStream input) {
System.out.println(FTP_ADDRESS);
boolean success = false;
FTPClient ftpClient = new FTPClient();
try {
login(ftpClient);
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode(); //用被动模式传输
ftpClient.setDataTimeout(30000); //设置超时时间
ftpClient.setBufferSize(1024 * 1024); //设置默认超时时间
ftpClient.makeDirectory(FTP_BASEPATH);
ftpClient.changeWorkingDirectory(FTP_BASEPATH);
success = ftpClient.storeFile(originFileName, input);
input.close();
Boolean close = closeConnect(ftpClient);
} catch (IOException e) {
log.error(e.getMessage(), e);
e.printStackTrace();
} finally {
Boolean close = closeConnect(ftpClient);
System.out.println("连接是否关闭:" + close);
}
return success;
}
public static Boolean uploadFile2(String fileName, InputStream inputStream, String ftpAddress, int ftpPort,
String ftpUserName, String ftpPassWord, String uploadPaasPath) {
FTP_ADDRESS = ftpAddress;
FTP_PORT = ftpPort;
FTP_USERNAME = ftpUserName;
FTP_PASSWORD = ftpPassWord;
FTP_BASEPATH = uploadPaasPath;
uploadFile2(fileName,inputStream);
return true;
}
public static InputStream downloadFileV2(String fileName, String attachmentPath) {
System.out.println(FTP_ADDRESS);
InputStream input = null;
InputStream resultOrginalStream = null;
FTPClient ftpClient = new FTPClient();
try {
boolean flag = login(ftpClient);
log.info("ftp登录" + flag);
log.info("***附件路径" + attachmentPath);
attachmentPath = attachmentPath.substring(0, attachmentPath.lastIndexOf("/"));
log.info("***附件路径" + attachmentPath);
ftpClient.changeWorkingDirectory("/home/paas_ftp" + attachmentPath);
} catch (IOException e1) {
try {
ftpClient.changeWorkingDirectory(FTP_BASEPATH);
} catch (IOException e2) {
e2.printStackTrace();
}
}
String remoteAbsoluteFile;
try {
remoteAbsoluteFile = toFtpFilename(fileName);
// 下载文件
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.setDataTimeout(60000);
ftpClient.setRemoteVerificationEnabled(false);
ftpClient.enterLocalPassiveMode();
// 设置传输类型为二进制;
ftpClient.setFileTransferMode(FTPClient.BINARY_FILE_TYPE);
input = ftpClient.retrieveFileStream(remoteAbsoluteFile);
resultOrginalStream = input;
input.close();
ftpClient.logout();
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(120000);
} catch (InterruptedException e) {
e.printStackTrace();
}
Boolean close = closeConnect(ftpClient);
System.out.println("连接是否关闭:" + close);
}
}).start();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return resultOrginalStream;
}