java模擬上傳附件,java附件上傳下載

本文目錄一覽:

java怎麼實現上傳附件的功能

上傳附件,實際上就是將文件存儲到遠程伺服器,進行臨時存儲。舉例:

**

* 上傳文件

*

* @param fileName

* @param plainFilePath 文件路徑路徑

* @param filepath

* @return

* @throws Exception

*/

public static String fileUploadByFtp(String plainFilePath, String fileName, String filepath) throws Exception {

FileInputStream fis = null;

ByteArrayOutputStream bos = null;

FTPClient ftpClient = new FTPClient();

String bl = “false”;

try {

fis = new FileInputStream(plainFilePath);

bos = new ByteArrayOutputStream(fis.available());

byte[] buffer = new byte[1024];

int count = 0;

while ((count = fis.read(buffer)) != -1) {

bos.write(buffer, 0, count);

}

bos.flush();

Log.info(“加密上傳文件開始”);

Log.info(“連接遠程上傳伺服器”+CCFCCBUtil.CCFCCBHOSTNAME+”:”+22);

ftpClient.connect(CCFCCBUtil.CCFCCBHOSTNAME, 22);

ftpClient.login(CCFCCBUtil.CCFCCBLOGINNAME, CCFCCBUtil.CCFCCBLOGINPASSWORD);

FTPFile[] fs;

fs = ftpClient.listFiles();

for (FTPFile ff : fs) {

if (ff.getName().equals(filepath)) {

bl=”true”;

ftpClient.changeWorkingDirectory(“/”+filepath+””);

}

}

Log.info(“檢查文件路徑是否存在:/”+filepath);

if(“false”.equals(bl)){

ViewUtil.dataSEErrorPerformedCommon( “查詢文件路徑不存在:”+”/”+filepath);

return bl;

}

ftpClient.setBufferSize(1024);

ftpClient.setControlEncoding(“GBK”);

// 設置文件類型(二進位)

ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

ftpClient.storeFile(fileName, fis);

Log.info(“上傳文件成功:”+fileName+”。文件保存路徑:”+”/”+filepath+”/”);

return bl;

} catch (Exception e) {

throw e;

} finally {

if (fis != null) {

try {

fis.close();

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e);

}

}

if (bos != null) {

try {

bos.close();

} catch (Exception e) {

Log.info(e.getLocalizedMessage(), e);

}

}

}

}

備註:只需要修改上傳的伺服器地址、用戶名、密碼即可進行伺服器訪問上傳。根據實際需要修改即可。

java 上傳附件實現方法

第一,jsp上傳頁面內容:

%@ page contentType=”text/html; charset=GBK” %

%@ taglib uri=”/WEB-INF/struts-html.tld” prefix=”html” %

html

head

title

jsp1

/title

/head

body bgcolor=”#ffffff”

html:form action=”myupload.do” method=”post” enctype=”multipart/form-data”

html:file property=”thisFile”/br

html:file property=”thisFile”/br

html:submit/

/html:form

/body

/html

第二,一個javabean

package upload;

import org.apache.struts.action.ActionForm;

import org.apache.struts.upload.FormFile;

import org.apache.struts.action.ActionErrors;

import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;

public class FileInfo extends ActionForm {

private FormFile thisFile;

public FormFile getThisFile() {

return thisFile;

}

public void setThisFile(FormFile thisFile) {

this.thisFile = thisFile;

}

public ActionErrors validate(ActionMapping actionMapping,

HttpServletRequest httpServletRequest) {

/** @todo: finish this method, this is just the skeleton.*/

return null;

}

public void reset(ActionMapping actionMapping,

HttpServletRequest servletRequest) {

}

}

第三,一個action

package upload;

import java.io.*;

import org.apache.struts.action.ActionMapping;

import org.apache.struts.action.ActionForm;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForward;

import org.apache.struts.action.Action;

import org.apache.struts.upload.FormFile;

public class myupload extends Action {

public ActionForward execute(ActionMapping actionMapping,

ActionForm actionForm,

HttpServletRequest request,

HttpServletResponse response) throws

FileNotFoundException, IOException {

FileInfo fileInfo = (FileInfo) actionForm;

//獲取上傳文件

FormFile f=fileInfo.getThisFile();

InputStream is=f.getInputStream();

//將文件存入伺服器上

String filename=request.getSession().getServletContext().getRealPath(“/shangchuan/”+f.getFileName());

OutputStream os=new FileOutputStream(filename);

int x=0;

//優化流處理過程

byte[] buffer = new byte[8192];

while((x=is.read(buffer, 0, 8192))!=-1)

{

os.write(buffer,0,x);

}

os.close();

response.sendRedirect(“jsp1.jsp”);//根據實際情況跳轉

return null;

}

}

怎麼用java發送帶附件的郵件代碼詳解

package email;  

import java.io.BufferedReader;   

import java.io.File;  

import java.io.FileInputStream;  

import java.io.FileNotFoundException;  

import java.io.IOException;  

import java.io.InputStream;  

import java.io.InputStreamReader;  

import java.io.PrintWriter;  

import java.io.UnsupportedEncodingException;  

import java.net.Socket;  

import java.nio.charset.Charset;  

import java.text.SimpleDateFormat;  

import java.util.ArrayList;  

import java.util.Date;  

import java.util.HashMap;  

import java.util.List;  

import java.util.Map;  

import sun.misc.BASE64Encoder;  

public class Mail {  

private static final String LINE_END = “\r\n”;  

private boolean isDebug = true;  

private boolean isAllowReadSocketInfo = true;  

private String host;  

private String from;  

private ListString to;  

private ListString cc;  

private ListString bcc;  

private String subject;  

private String user;  

private String password;  

private String contentType;  

private String boundary;  

private String boundaryNextPart;  

private String contentTransferEncoding;  

private String charset;  

private String contentDisposition;  

private String content;  

private String simpleDatePattern;  

private String defaultAttachmentContentType;  

private ListMailPart partSet;  

private static MapString, String contentTypeMap;  

static {  

// MIME Media Types  

contentTypeMap = new HashMapString, String();  

contentTypeMap.put(“xls”, “application/vnd.ms-excel”);  

contentTypeMap.put(“xlsx”, “application/vnd.ms-excel”);  

contentTypeMap.put(“xlsm”, “application/vnd.ms-excel”);  

contentTypeMap.put(“xlsb”, “application/vnd.ms-excel”);  

contentTypeMap.put(“doc”, “application/msword”);  

contentTypeMap.put(“dot”, “application/msword”);  

contentTypeMap.put(“docx”, “application/msword”);  

contentTypeMap.put(“docm”, “application/msword”);  

contentTypeMap.put(“dotm”, “application/msword”);  

}  

private class MailPart extends Mail {  

public MailPart() {  

}  

}  

public Mail() {  

defaultAttachmentContentType = “application/octet-stream”;  

simpleDatePattern = “yyyy-MM-dd HH:mm:ss”;  

boundary = “–=_NextPart_zlz_3907_” + System.currentTimeMillis();  

boundaryNextPart = “–” + boundary;  

contentTransferEncoding = “base64”;  

contentType = “multipart/alternative”;  

charset = Charset.defaultCharset().name();  

partSet = new ArrayListMailPart();  

to = new ArrayListString();  

cc = new ArrayListString();  

bcc = new ArrayListString();  

}  

private String getPartContentType(String fileName) {  

String ret = null;  

if (null != fileName) {  

int flag = fileName.lastIndexOf(“.”);  

if (0 = flag  flag  fileName.length() – 1) {  

fileName = fileName.substring(flag + 1);  

}  

ret = contentTypeMap.get(fileName);  

}  

if (null == ret) {  

ret = defaultAttachmentContentType;  

}  

return ret;  

}  

private String toBase64(String str, String charset) {  

if (null != str) {  

try {  

return toBase64(str.getBytes(charset));  

} catch (UnsupportedEncodingException e) {  

e.printStackTrace();  

}  

}  

return “”;  

}  

private String toBase64(byte[] bs) {  

return new BASE64Encoder().encode(bs);  

}  

private String toBase64(String str) {  

return toBase64(str, Charset.defaultCharset().name());  

}  

private String getAllParts() {  

int partCount = partSet.size();  

StringBuilder sbd = new StringBuilder(LINE_END);  

for (int i = partCount – 1; i = 0; i–) {  

Mail attachment = partSet.get(i);  

String attachmentContent = attachment.getContent();  

if (null != attachmentContent  0  attachmentContent.length()) {  

sbd.append(getBoundaryNextPart()).append(LINE_END);  

sbd.append(“Content-Type: “);  

sbd.append(attachment.getContentType());  

sbd.append(LINE_END);  

sbd.append(“Content-Transfer-Encoding: “);  

sbd.append(attachment.getContentTransferEncoding());  

sbd.append(LINE_END);  

if (i != partCount – 1) {  

sbd.append(“Content-Disposition: “);  

sbd.append(attachment.getContentDisposition());  

sbd.append(LINE_END);  

}  

sbd.append(LINE_END);  

sbd.append(attachment.getContent());  

sbd.append(LINE_END);  

}  

}  

sbd.append(LINE_END);  

sbd.append(LINE_END);  

partSet.clear();  

return sbd.toString();  

}  

private void addContent() {  

if (null != content) {  

MailPart part = new MailPart();  

part.setContent(toBase64(content));  

part.setContentType(“text/plain;charset=\”” + charset + “\””);  

partSet.add(part);  

}  

}  

private String listToMailString(ListString mailAddressList) {  

StringBuilder sbd = new StringBuilder();  

if (null != mailAddressList) {  

int listSize = mailAddressList.size();  

for (int i = 0; i  listSize; i++) {  

if (0 != i) {  

sbd.append(“;”);  

}  

sbd.append(“”).append(mailAddressList.get(i)).append(“”);  

}  

}  

return sbd.toString();  

}  

private ListString getrecipient() {  

ListString list = new ArrayListString();  

list.addAll(to);  

list.addAll(cc);  

list.addAll(bcc);  

return list;  

}  

public void addAttachment(String filePath) {  

addAttachment(filePath, null);  

}  

public void addTo(String mailAddress) {  

this.to.add(mailAddress);  

}  

public void addCc(String mailAddress) {  

this.cc.add(mailAddress);  

}  

public void addBcc(String mailAddress) {  

this.bcc.add(mailAddress);  

}  

public void addAttachment(String filePath, String charset) {  

if (null != filePath  filePath.length()  0) {  

File file = new File(filePath);  

try {  

addAttachment(file.getName(), new FileInputStream(file),  

charset);  

} catch (FileNotFoundException e) {  

System.out.println(“錯誤:” + e.getMessage());  

System.exit(1);  

}  

}  

}

上傳附件 java 代碼

SmartUpload上傳圖片

記得下載jar包啊

別忘了把名改成smartUpload.jar

Utility類:

package com.tidyinfo.utils;

import java.util.Calendar;

public class Utility {

//生成形如:\2006\08\18的路徑

private String path;

//生成形如: 20060818125012的唯一id號

private String id;

//生成形如:/2006/08/18的路徑

private String url;

private String hour;

private String year;

private String month;

private String day;

private String minate;

private String second;

/** Creates a new instance of Utility */

public Utility() {

this.year =new Integer(Calendar.getInstance().get(Calendar.YEAR)).toString();

this.month = parseToString(Calendar.getInstance().get(Calendar.MONTH)+1);

this.day = parseToString(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));

this.hour = parseToString(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));

this.minate = parseToString(Calendar.getInstance().get(Calendar.MINUTE));

this.second = parseToString(Calendar.getInstance().get(Calendar.SECOND));

this.setId();

this.setPath();

this.setUrl();

}

protected String parseToString(int i){

return i10?(“0″+i):new Integer(i).toString();

}

public String getId(){

return this.id;

}

public String getPath(){

return this.path;

}

public String getUrl(){

return this.url;

}

protected void setId(){

this.id = this.year+this.month+this.day+this.hour+this.minate+this.second;

}

protected void setPath(){

this.path = “\\”+this.year + “\\” + this.month + “\\” +

this.day ;

}

protected void setUrl(){

this.url = this.path.replace(‘\\’,’/’);

}

}

Action:(根據不同情況要更改相關代碼)

User userForm = new User();

String result = new String();

SmartUpload su = new SmartUpload();

//文件名

String filename = new String();

//文件擴展名

String fileext = new String();

//文件上傳後存儲的路徑

String path = request.getRealPath(request.getContextPath());

path = path.substring(0,path.lastIndexOf(“\\”));

path += “\\images”;

//圖片的url

String url = new String();

//創建文件夾

java.io.File file = new java.io.File(path);

file.mkdirs();

try{

// 上傳初始化

su.initialize(this.servlet.getServletConfig(),request,response);

//設定上傳限制

//1.限制每個上傳照片的最大長度。

su.setMaxFileSize(5000000);

//2.限制總上傳數據的長度。

su.setTotalMaxFileSize(10000000);

//3.設定允許上傳的照片(通過擴展名限制)。

su.setAllowedFilesList(“jpg,gif,GIF,JPG”);

//上傳照片

su.upload();

//獲得請求的表單數據

String username = su.getRequest().getParameter(“username”);//username

String password = su.getRequest().getParameter(“password”);//password

String sex = su.getRequest().getParameter(“sex”);//sex

String email =su.getRequest().getParameter(“email”);//email

String apwd =su.getRequest().getParameter(“apwd”);//question of password

String rpwd =su.getRequest().getParameter(“rpwd”);//anser of password

userForm.setUsername(username);

userForm.setPassword(password);

userForm.setSex(sex);

userForm.setEmail(email);

userForm.setApwd(apwd);

userForm.setRpwd(rpwd);

//將上傳照片全部保存到指定目錄

if(!su.getFiles().getFile(0).isMissing()){

su.save(path,su.SAVE_PHYSICAL);

//文件名

filename = su.getFiles().getFile(0).getFileName();

//得到擴展名

fileext = su.getFiles().getFile(0).getFileExt();

//給圖片改名,命名形如:20060814135411.gif

Utility u = new Utility();

String newName = u.getId()+”.”+fileext;

java.io.File oldFile = new java.io.File(path+”\\”+filename);

java.io.File newFile = new java.io.File( path + “\\”+newName);

//上傳圖片的url

url = request.getContextPath()+”/images/”+newName;

if(oldFile!=null){

oldFile.renameTo(newFile);

}else{

result+=”命名出錯!”;

}

System.out.println(“0000000000000000000″+filename);

System.out.println(“0000000000000000000″+path+”\\”+newName);

System.out.println(“0000000000000000000″+url);

System.out.println(result);

}

}catch(com.jspsmart.upload.SmartUploadException e){

result += “file出錯信息:”;

result += e.getMessage();

System.out.println(result);

}

java 代碼發郵件怎麼添加附件

實現java發送郵件的過程大體有以下幾步:

準備一個properties文件,該文件中存放SMTP伺服器地址等參數。

利用properties創建一個Session對象

利用Session創建Message對象,然後設置郵件主題和正文

利用Transport對象發送郵件

需要的jar有2個:activation.jar和mail.jar發送附件,需要用到Multipart對象。

import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

import javax.activation.DataHandler;

import javax.activation.DataSource;

import javax.activation.FileDataSource;

import javax.mail.BodyPart;

import javax.mail.Message;

import javax.mail.MessagingException;

import javax.mail.Multipart;

import javax.mail.Session;

import javax.mail.Transport;

import javax.mail.internet.InternetAddress;

import javax.mail.internet.MimeBodyPart;

import javax.mail.internet.MimeMessage;

import javax.mail.internet.MimeMultipart;

import javax.mail.internet.MimeUtility;

public class JavaMailWithAttachment {

    private MimeMessage message;

    private Session session;

    private Transport transport;

    private String mailHost = “”;

    private String sender_username = “”;

    private String sender_password = “”;

    private Properties properties = new Properties();

    /*

     * 初始化方法

     */

    public JavaMailWithAttachment(boolean debug) {

        InputStream in = JavaMailWithAttachment.class.getResourceAsStream(“MailServer.properties”);

        try {

            properties.load(in);

            this.mailHost = properties.getProperty(“mail.smtp.host”);

            this.sender_username = properties.getProperty(“mail.sender.username”);

            this.sender_password = properties.getProperty(“mail.sender.password”);

        } catch (IOException e) {

            e.printStackTrace();

        }

        session = Session.getInstance(properties);

        session.setDebug(debug);// 開啟後有調試信息

        message = new MimeMessage(session);

    }

    /**

     * 發送郵件

     * 

     * @param subject

     *            郵件主題

     * @param sendHtml

     *            郵件內容

     * @param receiveUser

     *            收件人地址

     * @param attachment

     *            附件

     */

    public void doSendHtmlEmail(String subject, String sendHtml, String receiveUser, File attachment) {

        try {

            // 發件人

            InternetAddress from = new InternetAddress(sender_username);

            message.setFrom(from);

            // 收件人

            InternetAddress to = new InternetAddress(receiveUser);

            message.setRecipient(Message.RecipientType.TO, to);

            // 郵件主題

            message.setSubject(subject);

            // 向multipart對象中添加郵件的各個部分內容,包括文本內容和附件

            Multipart multipart = new MimeMultipart();

            

            // 添加郵件正文

            BodyPart contentPart = new MimeBodyPart();

            contentPart.setContent(sendHtml, “text/html;charset=UTF-8”);

            multipart.addBodyPart(contentPart);

            

            // 添加附件的內容

            if (attachment != null) {

                BodyPart attachmentBodyPart = new MimeBodyPart();

                DataSource source = new FileDataSource(attachment);

                attachmentBodyPart.setDataHandler(new DataHandler(source));

                

                // 網上流傳的解決文件名亂碼的方法,其實用MimeUtility.encodeWord就可以很方便的搞定

                // 這裡很重要,通過下面的Base64編碼的轉換可以保證你的中文附件標題名在發送時不會變成亂碼

                //sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();

                //messageBodyPart.setFileName(“=?GBK?B?” + enc.encode(attachment.getName().getBytes()) + “?=”);

                

                //MimeUtility.encodeWord可以避免文件名亂碼

                attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));

                multipart.addBodyPart(attachmentBodyPart);

            }

            

            // 將multipart對象放到message中

            message.setContent(multipart);

            // 保存郵件

            message.saveChanges();

            transport = session.getTransport(“smtp”);

            // smtp驗證,就是你用來發郵件的郵箱用戶名密碼

            transport.connect(mailHost, sender_username, sender_password);

            // 發送

            transport.sendMessage(message, message.getAllRecipients());

            System.out.println(“send success!”);

        } catch (Exception e) {

            e.printStackTrace();

        } finally {

            if (transport != null) {

                try {

                    transport.close();

                } catch (MessagingException e) {

                    e.printStackTrace();

                }

            }

        }

    }

    public static void main(String[] args) {

        JavaMailWithAttachment se = new JavaMailWithAttachment(true);

        File affix = new File(“c:\\測試-test.txt”);

        se.doSendHtmlEmail(“郵件主題”, “郵件內容”, “xxx@XXX.com”, affix);//

    }

}

原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/272425.html

(0)
打賞 微信掃一掃 微信掃一掃 支付寶掃一掃 支付寶掃一掃
小藍的頭像小藍
上一篇 2024-12-17 13:55
下一篇 2024-12-17 13:56

相關推薦

  • java client.getacsresponse 編譯報錯解決方法

    java client.getacsresponse 編譯報錯是Java編程過程中常見的錯誤,常見的原因是代碼的語法錯誤、類庫依賴問題和編譯環境的配置問題。下面將從多個方面進行分析…

    編程 2025-04-29
  • Java JsonPath 效率優化指南

    本篇文章將深入探討Java JsonPath的效率問題,並提供一些優化方案。 一、JsonPath 簡介 JsonPath是一個可用於從JSON數據中獲取信息的庫。它提供了一種DS…

    編程 2025-04-29
  • Java Bean載入過程

    Java Bean載入過程涉及到類載入器、反射機制和Java虛擬機的執行過程。在本文中,將從這三個方面詳細闡述Java Bean載入的過程。 一、類載入器 類載入器是Java虛擬機…

    編程 2025-04-29
  • Java騰訊雲音視頻對接

    本文旨在從多個方面詳細闡述Java騰訊雲音視頻對接,提供完整的代碼示例。 一、騰訊雲音視頻介紹 騰訊雲音視頻服務(Cloud Tencent Real-Time Communica…

    編程 2025-04-29
  • Java Milvus SearchParam withoutFields用法介紹

    本文將詳細介紹Java Milvus SearchParam withoutFields的相關知識和用法。 一、什麼是Java Milvus SearchParam without…

    編程 2025-04-29
  • Java 8中某一周的周一

    Java 8是Java語言中的一個版本,於2014年3月18日發布。本文將從多個方面對Java 8中某一周的周一進行詳細的闡述。 一、數組處理 Java 8新特性之一是Stream…

    編程 2025-04-29
  • Java判斷字元串是否存在多個

    本文將從以下幾個方面詳細闡述如何使用Java判斷一個字元串中是否存在多個指定字元: 一、字元串遍歷 字元串是Java編程中非常重要的一種數據類型。要判斷字元串中是否存在多個指定字元…

    編程 2025-04-29
  • VSCode為什麼無法運行Java

    解答:VSCode無法運行Java是因為默認情況下,VSCode並沒有集成Java運行環境,需要手動添加Java運行環境或安裝相關插件才能實現Java代碼的編寫、調試和運行。 一、…

    編程 2025-04-29
  • Java任務下發回滾系統的設計與實現

    本文將介紹一個Java任務下發回滾系統的設計與實現。該系統可以用於執行複雜的任務,包括可回滾的任務,及時恢復任務失敗前的狀態。系統使用Java語言進行開發,可以支持多種類型的任務。…

    編程 2025-04-29
  • Java 8 Group By 會影響排序嗎?

    是的,Java 8中的Group By會對排序產生影響。本文將從多個方面探討Group By對排序的影響。 一、Group By的概述 Group By是SQL中的一種常見操作,它…

    編程 2025-04-29

發表回復

登錄後才能評論