java 如何推送附件
使用 JavaMail API 发送带附件的邮件
引入 JavaMail 依赖(Maven 项目):
<dependency>
<groupId>com.sun.mail</groupId>
<artifactId>javax.mail</artifactId>
<version>1.6.2</version>
</dependency>
创建邮件并添加附件:
Properties props = new Properties();
props.put("mail.smtp.host", "smtp.example.com");
props.put("mail.smtp.port", "587");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
Session session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication("username", "password");
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("from@example.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("to@example.com"));
message.setSubject("Email with Attachment");
Multipart multipart = new MimeMultipart();
// 邮件正文
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This email contains an attachment");
multipart.addBodyPart(messageBodyPart);
// 添加附件
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(new File("path/to/attachment.pdf"));
multipart.addBodyPart(attachmentPart);
message.setContent(multipart);
Transport.send(message);
} catch (Exception e) {
e.printStackTrace();
}
使用 HTTP 客户端发送带附件的请求
使用 Apache HttpClient 发送 multipart/form-data 请求:
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("http://example.com/upload");
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.addTextBody("field1", "value1", TEXT_PLAIN);
builder.addBinaryBody("file", new File("path/to/file"), ContentType.APPLICATION_OCTET_STREAM, "filename.ext");
HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
CloseableHttpResponse response = httpClient.execute(uploadFile);
HttpEntity responseEntity = response.getEntity();
使用 Spring Boot 上传文件
创建文件上传控制器:
@RestController
public class FileUploadController {
@PostMapping("/upload")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
try {
byte[] bytes = file.getBytes();
Path path = Paths.get("uploads/" + file.getOriginalFilename());
Files.write(path, bytes);
return ResponseEntity.ok("File uploaded successfully");
} catch (IOException e) {
return ResponseEntity.status(500).body("Upload failed");
}
}
}
使用 FTP 协议上传文件
使用 Apache Commons Net 进行 FTP 文件传输:

FTPClient ftpClient = new FTPClient();
try {
ftpClient.connect("ftp.example.com");
ftpClient.login("username", "password");
ftpClient.enterLocalPassiveMode();
File localFile = new File("local/path/file.txt");
InputStream inputStream = new FileInputStream(localFile);
boolean success = ftpClient.storeFile("remote/path/file.txt", inputStream);
inputStream.close();
if (success) {
System.out.println("File uploaded successfully");
}
} finally {
if (ftpClient.isConnected()) {
ftpClient.logout();
ftpClient.disconnect();
}
}






