當前位置:首頁 » 文件傳輸 » java上傳附件
擴展閱讀
webinf下怎麼引入js 2023-08-31 21:54:13
堡壘機怎麼打開web 2023-08-31 21:54:11

java上傳附件

發布時間: 2022-02-26 05:32:13

1. java上傳附件資料庫怎麼設計

2種方式;

  1. 保存文件路徑;

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

2. 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");

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

3. 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能獲取一個輸出流。

4. 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();
}

5. 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;
}

6. 上傳附件 java 代碼

SmartUpload上傳圖片

記得下載jar包啊
別忘了把名改成smartUpload.jar
http://www.ciw.com.cn/blog/UploadFiles/2006-8/816529534.rar

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 i<10?("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);
}

7. java實現文件上傳,代碼盡量簡潔~~~~~·

普通方法實現任意上傳?本地文件?本地文件直接用FileInputStream即可。
jspsmartupload需要在提交的form表單中添加一個屬性,具體內容忘了=。=

8. 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;
}
}

9. 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);
}
}
}
}
備註:只需要修改上傳的伺服器地址、用戶名、密碼即可進行伺服器訪問上傳。根據實際需要修改即可。