當前位置:首頁 » 文件管理 » java上傳附件

java上傳附件

發布時間: 2022-02-02 17:05:19

java上傳文件怎麼實現的

  • common-fileupload是jakarta項目組開發的一個功能很強大的上傳文件組件

  • 下面先介紹上傳文件到伺服器(多文件上傳):

  • import javax.servlet.*;

  • import javax.servlet.http.*;

  • import java.io.*;

  • import java.util.*;

  • import java.util.regex.*;

  • import org.apache.commons.fileupload.*;

  • public class upload extends HttpServlet {

  • private static final String CONTENT_TYPE = "text/html; charset=GB2312";

  • //Process the HTTP Post request

  • public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

  • response.setContentType(CONTENT_TYPE);

  • PrintWriter out=response.getWriter();

  • try {

  • DiskFileUpload fu = new DiskFileUpload();

  • // 設置允許用戶上傳文件大小,單位:位元組,這里設為2m

  • fu.setSizeMax(2*1024*1024);

  • // 設置最多隻允許在內存中存儲的數據,單位:位元組

  • fu.setSizeThreshold(4096);

  • // 設置一旦文件大小超過getSizeThreshold()的值時數據存放在硬碟的目錄

  • fu.setRepositoryPath("c://windows//temp");

  • //開始讀取上傳信息

  • List fileItems = fu.parseRequest(request);

  • // 依次處理每個上傳的文件

  • Iterator iter = fileItems.iterator();

  • //正則匹配,過濾路徑取文件名

  • String regExp=".+////(.+)$";

  • //過濾掉的文件類型

  • String[] errorType={".exe",".com",".cgi",".asp"};

  • Pattern p = Pattern.compile(regExp);

  • while (iter.hasNext()) {

  • FileItem item = (FileItem)iter.next();

  • //忽略其他不是文件域的所有表單信息

  • if (!item.isFormField()) {

  • String name = item.getName();

  • long size = item.getSize();

  • if((name==null||name.equals("")) && size==0)

  • continue;

  • Matcher m = p.matcher(name);

  • boolean result = m.find();

  • if (result){

  • for (int temp=0;temp<ERRORTYPE.LENGTH;TEMP++){

  • if (m.group(1).endsWith(errorType[temp])){

  • throw new IOException(name+": wrong type");

  • }

  • }

  • try{

  • //保存上傳的文件到指定的目錄

  • //在下文中上傳文件至資料庫時,將對這里改寫

  • item.write(new File("d://" + m.group(1)));

  • out.print(name+" "+size+"");

  • }

  • catch(Exception e){

  • out.println(e);

  • }

  • }

  • else

  • {

  • throw new IOException("fail to upload");

  • }

  • }

  • }

  • }

  • catch (IOException e){

  • out.println(e);

  • }

  • catch (FileUploadException e){

  • out.println(e);

  • }

  • }

  • }

  • 現在介紹上傳文件到伺服器,下面只寫出相關代碼:

  • sql2000為例,表結構如下:

  • 欄位名:name filecode

  • 類型: varchar image

  • 資料庫插入代碼為:PreparedStatement pstmt=conn.prepareStatement("insert into test values(?,?)");

  • 代碼如下:

  • 。。。。。。

  • try{

  • 這段代碼如果不去掉,將一同寫入到伺服器中

  • //item.write(new File("d://" + m.group(1)));

  • int byteread=0;

  • //讀取輸入流,也就是上傳的文件內容

  • InputStream inStream=item.getInputStream();

  • pstmt.setString(1,m.group(1));

  • pstmt.setBinaryStream(2,inStream,(int)size);

  • pstmt.executeUpdate();

  • inStream.close();

  • out.println(name+" "+size+" ");

  • }

  • 。。。。。。

  • 這樣就實現了上傳文件至資料庫

Ⅱ java中怎樣上傳文件

Java代碼實現文件上傳

FormFilefile=manform.getFile();
StringnewfileName=null;
Stringnewpathname=null;
StringfileAddre="/numUp";
try{
InputStreamstream=file.getInputStream();//把文件讀入
StringfilePath=request.getRealPath(fileAddre);//取系統當前路徑
Filefile1=newFile(filePath);//添加了自動創建目錄的功能
((File)file1).mkdir();
newfileName=System.currentTimeMillis()
+file.getFileName().substring(
file.getFileName().lastIndexOf('.'));
ByteArrayOutputStreambaos=newByteArrayOutputStream();
OutputStreambos=newFileOutputStream(filePath+"/"
+newfileName);
newpathname=filePath+"/"+newfileName;
System.out.println(newpathname);
//建立一個上傳文件的輸出流
System.out.println(filePath+"/"+file.getFileName());
intbytesRead=0;
byte[]buffer=newbyte[8192];
while((bytesRead=stream.read(buffer,0,8192))!=-1){
bos.write(buffer,0,bytesRead);//將文件寫入伺服器
}
bos.close();
stream.close();
}catch(FileNotFoundExceptione){
e.printStackTrace();
}catch(IOExceptione){
e.printStackTrace();
}

Ⅲ java文件上傳問題

第一句就是創建一個Map對象

第二句是獲取:文件上傳的路徑

例如:

StringrealPath=ServletActionContext.getServletContext().getRealPath(
"/upload");
FileUtils.File(file,newFile(realPath,fileFileName));

上傳以後圖片的位置:

Ⅳ java如何實現文件上傳

public static int transFile(InputStream in, OutputStream out, int fileSize) {
int receiveLen = 0;
final int bufSize = 1000;
try {
byte[] buf = new byte[bufSize];
int len = 0;
while(fileSize - receiveLen > bufSize)
{
len = in.read(buf);
out.write(buf, 0, len);
out.flush();
receiveLen += len;
System.out.println(len);
}
while(receiveLen < fileSize)
{
len = in.read(buf, 0, fileSize - receiveLen);
System.out.println(len);
out.write(buf, 0, len);
receiveLen += len;
out.flush();
}
} catch (IOException e) {
// TODO 自動生成 catch 塊
e.printStackTrace();
}
return receiveLen;
}
這個方法從InputStream中讀取內容,寫到OutputStream中。
那麼發送文件方,InputStream就是FileInputStream,OutputStream就是Socket.getOutputStream.
接受文件方,InputStream就是Socket.getInputStream,OutputStream就是FileOutputStream。
就OK了。 至於存到資料庫里嘛,Oracle里用Blob。搜索一下,也是一樣的。從Blob能獲取一個輸出流。

Ⅳ Java文件上傳的幾種方式

1、通過Servlet類上傳
2、通過Struts框架實現上傳
ITJOB學到兩種方式

Ⅵ java實現文件的上傳和下載

用輸出流 接受 一個下載地址的網路流
然後將這個輸出流 保存到本地一個文件 後綴與下載地址的後綴相同··

上傳的話 將某個文件流 轉成位元組流 上傳到某個webservice方法里

-------要代碼來代碼

URL url=new URL("http://www..com/1.rar");
URLConnection uc=url.openConnection();
InputStream in=uc.getInputStream();
BufferedInputStream bis=new BufferedInputStream(in);
FileOutputStream ft=new FileOutputStream("E://1.rar");

這是下載 上傳太麻煩就不給寫了

Ⅶ 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上傳附件資料庫怎麼設計

2種方式;

  1. 保存文件路徑;

  2. 將文件寫入資料庫,使用blob欄位

Ⅸ java上傳文件怎麼弄

jsp: <input id="file" name="doc" type="file" style="position:absolute;filter:alpha(opacity=0);width:152px;height:120px;top:40px;left:10px" >

public String dbUpload(){
ActionContext ctx = ActionContext.getContext();
HttpServletRequest req = (HttpServletRequest) ctx.get(ServletActionContext.HTTP_REQUEST);
MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper)req;
File doc =wrapper.getFile("doc");
String fileName=null;
if(doc!=null){
fileName="/"+String.valueOf(System.currentTimeMillis())+"."+wrapper.getContentTypes("doc")[0].substring(6);
try {
// String dri=req.getRealPath("img"); //代表圖片上傳的地方為img文件夾
String dri=imagdirectory;
File target =new File(dri+fileName);
FileUtils.File(doc, target);
}catch(Exception e) {
e.printStackTrace();
}finally {
if(doc.exists()){
doc.delete();
}

}
}
return fileName;
}

熱點內容
ip伺服器哪裡買 發布:2024-10-21 22:49:56 瀏覽:297
美女壓縮包 發布:2024-10-21 22:24:04 瀏覽:319
c語言創建按鈕 發布:2024-10-21 22:13:49 瀏覽:730
筆記本賬戶密碼是什麼 發布:2024-10-21 22:03:47 瀏覽:908
榮耀俱樂部怎麼退回安卓 發布:2024-10-21 22:02:35 瀏覽:963
androidxmlmenu 發布:2024-10-21 22:00:35 瀏覽:390
安卓光遇截圖保存在哪裡 發布:2024-10-21 21:47:39 瀏覽:485
sqlservermd5加密 發布:2024-10-21 21:33:51 瀏覽:863
python網頁編碼 發布:2024-10-21 21:33:08 瀏覽:477
移動數據最快的伺服器地址是多少 發布:2024-10-21 21:31:56 瀏覽:516