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

java附件上傳

發布時間: 2022-02-18 04:27:39

java附件上傳功能,上傳的附件要根據時間來重命名,上傳的路徑保存在伺服器指定目錄根據年月來分的目錄里

如果使用框架的話,比如 struts ,就比較簡單了
獲取上傳的時間:
Calendar cal = Calendar.getInstance();
String year = String.valueOf(cal.get(Calendar.YEAR));
String month = String.valueOf(cal.get(Calendar.MONTH));
獲取路徑:
String path = ServletActionContext.getServletContext().getRealPath("/"+year+"/"+month);
直接保存在 path 這個目錄裡面就可以

如果沒有使用 框架,可以使用 FileUpload 這個 jar 包來上傳文件

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

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

Ⅲ 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實現文件的上傳和下載

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

上傳的話 將某個文件流 轉成位元組流 上傳到某個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中怎樣上傳文件

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 流式文件上傳

@Controller
public class UploadController extends BaseController {

private static final Log log = LogFactory.getLog(UploadController.class);
private UploadService uploadService;
private AuthService authService;

/**
* 大文件分成小文件塊上傳,一次傳遞一塊,最後一塊上傳成功後,將合並所有已經上傳的塊,保存到File Server
* 上相應的位置,並返回已經成功上傳的文件的詳細屬性. 當最後一塊上傳完畢,返回上傳成功的信息。此時用getFileList查詢該文件,
* 該文件的uploadStatus為2。client請自行處理該狀態下文件如何顯示。(for UPS Server)
*
*/
@RequestMapping("/core/v1/file/upload")
@ResponseBody
public Object upload(HttpServletResponse response,
@RequestParam(value = "client_id", required = false) String appkey,
@RequestParam(value = "sig", required = false) String appsig,
@RequestParam(value = "token", required = false) String token,
@RequestParam(value = "uuid", required = false) String uuid,
@RequestParam(value = "block", required = false) String blockIndex,
@RequestParam(value = "file", required = false) MultipartFile multipartFile,
@RequestParam Map<String, String> parameters) {

checkEmpty(appkey, BaseException.ERROR_CODE_16002);
checkEmpty(token, BaseException.ERROR_CODE_16007);
checkEmpty(uuid, BaseException.ERROR_CODE_20016);
checkEmpty(blockIndex, BaseException.ERROR_CODE_20006);
checkEmpty(appsig, BaseException.ERROR_CODE_10010);
if (multipartFile == null) {
throw new BaseException(BaseException.ERROR_CODE_20020);// 上傳文件不存在
}
Long uuidL = parseLong(uuid, BaseException.ERROR_CODE_20016);
Integer blockIndexI = parseInt(blockIndex, BaseException.ERROR_CODE_20006);

Map<String, Object> appMap = getAuthService().validateSigature(parameters);

AccessToken accessToken = CasUtil.checkAccessToken(token, appMap);
Long uid = accessToken.getUid();
String bucketUrl = accessToken.getBucketUrl();
// 從上傳目錄拷貝文件到工作目錄
String fileAbsulutePath = null;
try {
fileAbsulutePath = this.File(multipartFile.getInputStream(), multipartFile.getOriginalFilename());
} catch (IOException ioe) {
log.error(ioe.getMessage(), ioe);
throw new BaseException(BaseException.ERROR_CODE_20020);// 上傳文件不存在
}
File uploadedFile = new File(Global.UPLOAD_TEMP_DIR + fileAbsulutePath);
checkEmptyFile(uploadedFile);// file 非空驗證

Object rs = uploadService.upload(uuidL, blockIndexI, uid, uploadedFile, bucketUrl);
setHttpStatusOk(response);
return rs;
}

// TODO 查看下這里是否有問題
// 上傳文件非空驗證
private void checkEmptyFile(File file) {
if (file == null || file.getAbsolutePath() == null) {
throw new BaseException(BaseException.ERROR_CODE_20020);// 上傳文件不存在
}
}

/**
* 寫文件到本地文件夾
*
* @throws IOException
* 返回生成的文件名
*/
private String File(InputStream inputStream, String fileName) {
OutputStream outputStream = null;
String tempFileName = null;
int pointPosition = fileName.lastIndexOf(".");
if (pointPosition < 0) {// myvedio
tempFileName = UUID.randomUUID().toString();// 94d1d2e0-9aad-4dd8-a0f6-494b0099ff26
} else {// myvedio.flv
tempFileName = UUID.randomUUID() + fileName.substring(pointPosition);// 94d1d2e0-9aad-4dd8-a0f6-494b0099ff26.flv
}
try {
outputStream = new FileOutputStream(Global.UPLOAD_TEMP_DIR + tempFileName);
int readBytes = 0;
byte[] buffer = new byte[10000];
while ((readBytes = inputStream.read(buffer, 0, 10000)) != -1) {
outputStream.write(buffer, 0, readBytes);
}
return tempFileName;
} catch (IOException ioe) {
// log.error(ioe.getMessage(), ioe);
throw new BaseException(BaseException.ERROR_CODE_20020);// 上傳文件不存在
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
}
}

}

}

/**
* 測試此服務是否可用
*
* @param response
* @return
* @author zwq7978
*/
@RequestMapping("/core/v1/file/testServer")
@ResponseBody
public Object testServer(HttpServletResponse response) {
setHttpStatusOk(response);
return Global.SUCCESS_RESPONSE;
}

public UploadService getUploadService() {
return uploadService;
}

public void setUploadService(UploadService uploadService) {
this.uploadService = uploadService;
}

public void setAuthService(AuthService authService) {
this.authService = authService;
}

public AuthService getAuthService() {
return authService;
}

}

Ⅶ java編程:我現在做一個附件上傳功能,現在已經可以成功上傳了,不過還有個要求,上傳後的文件需要壓縮

使用壓縮流。如下:

http://blog.csdn.net/hanshileiai/article/details/6718375
修改名字不是太簡單了么?在定義File的時候就改成你要的名字不就行了。

Ⅷ 用java實現文件的上傳與下載

1.下載簡單,無非是把伺服器上的文件或者資料庫中的BLob(或其他二進制型),用流讀出來,然後寫到客戶端即可,要注意 ContentType。

2.上傳,可以用Apache Commons Upload等開源工具,或者自己寫:
form要用enctype="multipart/form-data"
然後伺服器端也是用IO把客戶端提交的文件流讀入,然後寫到伺服器的文件系統或者資料庫里。不同的資料庫對Lob欄位操作可能有所不同,建議用Hibernate,JPA等成熟的ORM框架,可以不考慮資料庫細節。

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

熱點內容
標准配置什麼意思 發布:2024-10-26 14:35:27 瀏覽:880
查看linux所有用戶 發布:2024-10-26 14:11:15 瀏覽:15
useraddftp 發布:2024-10-26 13:59:21 瀏覽:621
安卓免費私密相冊哪個好用 發布:2024-10-26 13:41:20 瀏覽:639
湛江移動伺服器ip 發布:2024-10-26 13:12:17 瀏覽:634
找回dns伺服器地址 發布:2024-10-26 12:48:23 瀏覽:240
王者皮膚系統腳本 發布:2024-10-26 12:46:44 瀏覽:508
電腦配置8g怎麼查看 發布:2024-10-26 12:40:58 瀏覽:811
布朗編程 發布:2024-10-26 12:35:27 瀏覽:307
php平滑重啟 發布:2024-10-26 12:25:33 瀏覽:948