『壹』 java 中如何向伺服器上傳圖片
我們使用一些已有的組件幫助我們實現這種上傳功能。
常用的上傳組件:
Apache 的 Commons FileUpload
JavaZoom的UploadBean
jspSmartUpload
以下,以FileUpload為例講解
1、在jsp端
<form id="form1" name="form1" method="post" action="servlet/fileServlet" enctype="multipart/form-data">
要注意enctype="multipart/form-data"
然後只需要放置一個file控制項,並執行submit操作即可
<input name="file" type="file" size="20" >
<input type="submit" name="submit" value="提交" >
2、web端
核心代碼如下:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List items = upload.parseRequest(request);
Iterator itr = items.iterator();
while (itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if (item.isFormField()) {
System.out.println("表單參數名:" + item.getFieldName() + ",表單參數值:" + item.getString("UTF-8"));
} else {
if (item.getName() != null && !item.getName().equals("")) {
System.out.println("上傳文件的大小:" + item.getSize());
System.out.println("上傳文件的類型:" + item.getContentType());
System.out.println("上傳文件的名稱:" + item.getName());
File tempFile = new File(item.getName());
File file = new File(sc.getRealPath("/") + savePath, tempFile.getName());
item.write(file);
request.setAttribute("upload.message", "上傳文件成功!");
}else{
request.setAttribute("upload.message", "沒有選擇上傳文件!");
}
}
}
}catch(FileUploadException e){
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
request.setAttribute("upload.message", "上傳文件失敗!");
}
request.getRequestDispatcher("/uploadResult.jsp").forward(request, response);
}
『貳』 java 圖片上傳
//1.初始化smartupload對象
SmartUpload su=new SmartUpload();
su.initialize(pageContext);
//2.定義上傳文件類型
su.setAllowedFilesList("gif,jpg,doc,txt");
//3.不允許上傳類型
su.setDeniedFilesList("jsp,asp,html,exe,bat");
//4.設置字元編碼、
su.setCharset("UTF-8");
//5.設置的單個上傳最大限制
su.setMaxFileSize(5*1024*1024);
//6.總共上傳限制
su.setTotalMaxFileSize(20*1024*1024);
//7.上傳
su.upload();
//su.getFiles().getCount() 獲取上傳數
File file=su.getFiles().getFile(0);
String filename=file.getFileName();
System.out.print(filename);
String filepath="upload\\";
filepath+=file.getFileName();
file.saveAs(filepath,SmartUpload.SAVE_VIRTUAL);
『叄』 Java 關於圖片上傳的功能
上傳圖片 type 類型 file form標簽 多個屬性 到伺服器上 的時候 是3個東西 一個是文件 一個是文件名 一個是文件類型 做處理 io 到 對應路徑 瀏覽時候 拿路徑 設置 img 尺寸,
img 點擊事件 變大 改變
網上搜索下狠多
『肆』 怎麼用Java實現圖片上傳
下面這是servlet的內容:
package demo;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class DemoServlet extends HttpServlet {
private static final String UPLOAD_DIRECTORY = "upload";
private static final int MEMORY_THRESHOLD = 1024 * 1024 * 3; // 3MB
private static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
private static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
DiskFileItemFactory factory=new DiskFileItemFactory();
ServletFileUpload sfu=new ServletFileUpload(factory);
sfu.setHeaderEncoding("UTF-8");
sfu.setProgressListener(new ProgressListener() {
public void update(long pBytesRead, long pContentLength, int pItems) {
System.out.println("文件大小為:"+pContentLength+",當前已處理:"+pBytesRead);
}
});
//判斷提交上來的數據是否是上傳表單的數據
if(!ServletFileUpload.isMultipartContent(request)){
PrintWriter writer= response.getWriter();
writer.println("Error:表單必須包含 enctype=multipart/form-data");
writer.flush();
return;
}
factory.setSizeThreshold(MEMORY_THRESHOLD);
//設置臨時儲存目錄
factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
//設置最大文件上傳值
sfu.setFileSizeMax(MAX_FILE_SIZE);
//設置最大請求值(包含文件和表單數據)
sfu.setSizeMax(MAX_REQUEST_SIZE);
String uploadpath=getServletContext().getRealPath("./")+ File.separator+UPLOAD_DIRECTORY;
File file=new File(uploadpath);
if(!file.exists()){
file.mkdir();
}
try {
List<FileItem> formItems = sfu.parseRequest(request);
if(formItems!=null&&formItems.size()>0){
for(FileItem item:formItems){
if(!item.isFormField()){
String fileName=new File(item.getName()).getName();
String filePath=uploadpath+File.separator+fileName;
File storeFile=new File(filePath);
System.out.println(filePath);
item.write(storeFile);
request.setAttribute("message", "文件上傳成功!");
}
}
}
} catch (Exception e) {
request.setAttribute("message", "錯誤信息:"+e.getMessage());
}
getServletContext().getRequestDispatcher("/demo.jsp").forward(request, response);
}
}
下面是jsp的內容,jsp放到webapp下,如果想放到WEB-INF下就把servlet里轉發的路徑改一下:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="demo.do" enctype="multipart/form-data" method="post">
<input type="file" name="file1" />
<%
String message = (String) request.getAttribute("message");
%>
<%=message%>
<input type="submit" value="提交"/>
</form>
</body>
</html>
這段代碼可以實現普通的文件上傳,有大小限制,上傳普通的圖片肯定沒問題,別的一些小的文件也能傳
『伍』 java怎樣上傳圖片(寫個例子謝謝);
我有一段上傳圖片的代碼,並且可以根據實際,按月或按天等,生成存放圖片的文件夾
首先在JSP上放一個FILE的標簽這些我都不說了,你也一定明白,我直接把處理過程給你發過去
我把其中存到資料庫中的內容刪除了,你改一下就能用
/**
*
* 上傳圖片
* @param servlet
* @param request
* @param response
* @return
* @throws Exception
*/
//這里我是同步上傳的,你隨意
public synchronized String importPic(HttpServlet servlet, HttpServletRequest request,HttpServletResponse response) throws Exception {
SimpleDate()Format formatDate() = new SimpleDate()Format("yyyyMM");
Date nowtime=new Date();
String formatnowtime=formatDate.format(nowtime);
File root = new File(request.getRealPath("/")+"uploadfile/images/"+formatnowtime+"/"); //應保證在根目錄中有此目錄的存在 如果沒有,下面則上創建新的文件夾
if(!root.isDirectory())
{
System.out.println("創建新文件夾成功"+formatnowtime);
root.mkdir();
}
int returnflag = 0;
SmartUpload mySmartUpload =new SmartUpload();
int file_size_max=1024000;
String ext="";
String url="uploadfile/images/"+formatnowtime+"/";
// 只允許上載此類文件
try{
// 初始化
mySmartUpload.initialize(servlet.getServletConfig(),request,response);
mySmartUpload.setAllowedFilesList("jpg,gif,bmp,jpeg,png,JPG");
// 上載文件
mySmartUpload.upload();
} catch (Exception e){
response.sendRedirect()//返回頁面
}
com.jspsmart.upload.File myFile = mySmartUpload.getFiles().getFile(0);
if (myFile.isMissing()){ //沒有選擇圖片做提示!
returnflag = 3;
}else{
String myFileName=myFile.getFileName(); //取得上載的文件的文件名
ext= myFile.getFileExt(); //取得後綴名
if(ext.equals("jpg")||ext.equals("gif")||ext.equals("bmp")||ext.equals("jpeg")||ext.equals("png")||ext.equals("JPG")){ //jpeg,png不能上傳!)
int file_size=myFile.getSize(); //取得文件的大小
String saveurl="";
if(file_size<file_size_max){
try{
//我上面說到,把操作資料庫的代友刪除了,這里就應該是判斷,你的圖片是不是已經存在了,存在要怎麼處理,不存在要怎麼處了,就是你的事了 }
//更改文件名,取得當前上傳時間的毫秒數值
Calendar calendar = Calendar.getInstance();
//String filename = String.valueOf(calendar.getTimeInMillis());
String did = contractBean.getMaxSeq("MULTIMEDIA_SEQ");
String filename = did;
String flag = "0";
String path = request.getRealPath("/")+url;
String ename = myFile.getFileExt();
//.toLowerCase()轉換大小寫
saveurl=request.getRealPath("/")+url;
saveurl+=filename+"."+ext; //保存路徑
myFile.saveAs(saveurl,mySmartUpload.SAVE_PHYSICAL);
//將圖片信息插入到資料庫中
// ------上傳完成,開始生成縮略圖-----
java.io.File file = new java.io.File(saveurl); //讀入剛才上傳的文件
String newurl=request.getRealPath("/")+url+filename+"_min."+ext; //新的縮略圖保存地址
Image src = javax.imageio.ImageIO.read(file); //構造Image對象
float tagsize=200;
int old_w=src.getWidth(null);
int old_h=src.getHeight(null);
int new_w=0;
int new_h=0;
int tempsize;
float tempdouble;
if(old_w>old_h){
tempdouble=old_w/tagsize;
}else{
tempdouble=old_h/tagsize;
}
// new_w=Math.round(old_w/tempdouble);
// new_h=Math.round(old_h/tempdouble);//計算新圖長寬
new_w=150;
new_h=110;//計算新圖長寬
BufferedImage tag = new BufferedImage(new_w,new_h,BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(src,0,0,new_w,new_h,null); //繪制縮小後的圖
FileOutputStream newimage=new FileOutputStream(newurl); //輸出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(newimage);
encoder.encode(tag); //近JPEG編碼
newimage.close();
returnflag = 1;
}else{
returnflag = 0;
System.out.println("('上傳文件大小不能超過"+(file_size_max/1000)+"K');");
}
}else{
returnflag = 2;
}
}
response.sendRedirect();
return "11";
}
『陸』 Java中如何圖片非同步上傳
在java中要實現非同步上傳要提前做好准備,對於文件上傳,瀏覽器在上傳的過程中是將文件以流的形式提交到伺服器端的,如果直接使用Servlet獲取上傳文件的輸入流然後再解析裡面的請求參數是比較麻煩,所以一般選擇採用apache的開源工具common-fileupload這個文件上傳組件。
這個common-fileupload上傳組件的jar包可以去apache官網上面下載,也可以在struts的lib文件夾下面找到,struts上傳的功能就是基於這個實現的。
common-fileupload是依賴於common-io這個包的,所以還需要下載這個包。剩下的就是js文件的導入了,我導入了以下文件:
<script type="text/javascript" src="lib/Js/jquery.js"></script>
<script ltype="text/javascript" src="/js/ajaxfileupload.js"></script>
在頁面中的寫法:
div class="controls"><span class="btn green fileinput-button"><i class="icon-plus icon-white"></i>
<span>上傳照片</span>
<input id="fileToUpload" name="myfiles" type="file" onchange="upload()" title="上傳" /></span>
</div>function upload(){
$.ajaxFileUpload
(
{
url:'<%=basePath%>sysperson/uploadpic',
secureuri:false,
fileElementId:'fileToUpload',
dataType: 'text',
success: function (data, status)
{
document.all.mypic.src="<%=basePath%>uploads/" + data;
document.all.picpath.value = data;
}, error : function(data, status, e) {
alert(e);
}
});
}
『柒』 java上傳圖片
/**
*
*/
package net.hlj.chOA.action;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.hlj.chOA..DangAnDao;
import net.hlj.chOA..LogDao;
import net.hlj.chOA..ZiYuanDao;
import net.hlj.chOA.model.DangAn;
import net.hlj.chOA.model.User;
import net.hlj.chOA.model.ZiYuan;
import net.hlj.chOA.util.GetId;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;
/**
* @author lcy
*
*/
public class ZiYuanAction extends DispatchAction {
public ActionForward addZiYuan(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
String title = "";
String fileupload="";
SimpleDateFormat fmt = new SimpleDateFormat("yyMMddhhssmmSSS");
Date now = new Date();
String date = fmt.format(now);
String filePath = request.getSession().getServletContext().getRealPath(
"/");
String uploadPath = filePath + "upload\\uploadZiYuan\\";
String tempPath = filePath + "upload\\uploadZiYuan\\" + "uploadTemp";
String suffix = null;
if (!new File(uploadPath).isDirectory()) {
new File(uploadPath).mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4194304);// 設置初始化內存,如果上傳的文件超過該大小,將不保存到內存,而且硬碟中(單位:byte)
File fileTemp = new File(tempPath);// 建立臨時目錄
fileTemp.mkdir();
factory.setRepository(fileTemp);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(4194304);// 設置客戶端最大上傳,-1為無限大(單位:byte)
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> i = items.iterator();
String[] rightType = {".gif", ".jpeg", ".doc", ".xls",
".pdf", ".txt", ".rar" };
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (fi.isFormField()) {
try {
if (fi.getFieldName().equals("title")) {
title = fi.getString("UTF-8");
}
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
}
} else {
String fileName = fi.getName();
int l = fileName.length();
if (!fileName.equals("")) {
int pos = fileName.lastIndexOf(".");
// suffix = fileName.substring(l - 4, l);
suffix = fileName.substring(pos, l);
boolean result = false;
String ext = fileName.substring(fileName
.lastIndexOf("."));
for (int j = 0; j < rightType.length; j++) {
if (ext.toLowerCase().equals(rightType[j])) {
result = true;
break;
}
}
if (!result) {
request.setAttribute("error", "上傳文件類型有誤!");
return mapping.findForward("addZiyuan");
}
// if (!suffix.equalsIgnoreCase(".jpg") &&
// !suffix.equalsIgnoreCase(".gif")
// && !suffix.equalsIgnoreCase(".png") &&
// !suffix.equalsIgnoreCase(".bmp")) {
// request.setAttribute("message", "上傳文件類型有誤!");
// return mapping.findForward("danganList");
// }
if (fileName != null) {
File savedFile = new File(uploadPath, date + suffix);
try {
fi.write(savedFile);
fileupload = "upload/uploadZiYuan/" + date
+ suffix;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}
}
}
} catch (FileUploadException e) {
log.error(e.getMessage(), e);
}
ZiYuan zy=new ZiYuan();
zy.setTitle(title);
zy.setUpload(fileupload);
ZiYuanDao zyDao=new ZiYuanDao();
try {
zyDao.addZiYuan(zy, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LogDao lDao=new LogDao();
//刪除操做添加日誌 isDel 0是增加,1是刪除,2是修改,3是審批
User user1 =(User)request.getSession().getAttribute("userBean");
String ip=request.getLocalAddr();
int id=GetId.getId("ziyuan", this.servlet.getServletContext());
try {
lDao.addLogMe("ziyuan", id , ip, user1.getName(), user1.getId(), 0, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mapping.findForward("ziyuanList");
}
public ActionForward deleteZiYuan(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) {
String[] ids= request.getParameterValues("id");
ZiYuanDao zyDao=new ZiYuanDao();
LogDao lDao=new LogDao();
for(int i=0;i<ids.length;i++){
try {
zyDao.deleteZiYuan(Integer.parseInt(ids[i]), this.servlet.getServletContext());
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
User user =(User)request.getSession().getAttribute("userBean");
String ip=request.getLocalAddr();
try {
lDao.addLogMe("tbl_users",Integer.parseInt(ids[i]), ip, user.getName(), user.getId(), 1, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return mapping.findForward("ziyuanList");
}
public ActionForward updateZiYuan(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response) throws NumberFormatException, SQLException {
String id="";
String title = "";
String fileupload="";
SimpleDateFormat fmt = new SimpleDateFormat("yyMMddhhssmmSSS");
Date now = new Date();
String date = fmt.format(now);
String filePath = request.getSession().getServletContext().getRealPath(
"/");
String uploadPath = filePath + "upload\\uploadZiYuan\\";
String tempPath = filePath + "upload\\uploadZiYuan\\" + "uploadTemp";
String suffix = null;
if (!new File(uploadPath).isDirectory()) {
new File(uploadPath).mkdirs();
}
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(4194304);// 設置初始化內存,如果上傳的文件超過該大小,將不保存到內存,而且硬碟中(單位:byte)
File fileTemp = new File(tempPath);// 建立臨時目錄
fileTemp.mkdir();
factory.setRepository(fileTemp);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(4194304);// 設置客戶端最大上傳,-1為無限大(單位:byte)
try {
List<FileItem> items = upload.parseRequest(request);
Iterator<FileItem> i = items.iterator();
String[] rightType = {".gif", ".jpeg", ".doc", ".xls",
".pdf", ".txt", ".rar" };
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (fi.isFormField()) {
try {
if (fi.getFieldName().equals("title")) {
title = fi.getString("UTF-8");
}
if (fi.getFieldName().equals("id")) {
id = fi.getString("UTF-8");
}
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(), e);
}
} else {
String fileName = fi.getName();
int l = fileName.length();
if (!fileName.equals("")) {
int pos = fileName.lastIndexOf(".");
// suffix = fileName.substring(l - 4, l);
suffix = fileName.substring(pos, l);
boolean result = false;
String ext = fileName.substring(fileName
.lastIndexOf("."));
for (int j = 0; j < rightType.length; j++) {
if (ext.toLowerCase().equals(rightType[j])) {
result = true;
break;
}
}
if (!result) {
request.setAttribute("error", "上傳文件類型有誤!");
request.setAttribute("id", id);
return mapping.findForward("selectZiyuan");
}
// if (!suffix.equalsIgnoreCase(".jpg") &&
// !suffix.equalsIgnoreCase(".gif")
// && !suffix.equalsIgnoreCase(".png") &&
// !suffix.equalsIgnoreCase(".bmp")) {
// request.setAttribute("message", "上傳文件類型有誤!");
// return mapping.findForward("danganList");
// }
if (fileName != null) {
File savedFile = new File(uploadPath, date + suffix);
try {
fi.write(savedFile);
fileupload = "upload/uploadZiYuan/" + date
+ suffix;
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
}else{
//這里寫如果用戶沒有重寫添加附件則保持原來的附件
ZiYuanDao zyDao = new ZiYuanDao();
ZiYuan zy=(ZiYuan)zyDao.selectZiYuanById(Integer.parseInt(id), this.servlet.getServletContext()).get(0);
fileupload=zy.getUpload();
}
}
}
} catch (FileUploadException e) {
log.error(e.getMessage(), e);
}
ZiYuan zy=new ZiYuan();
zy.setId(Integer.parseInt(id));
zy.setTitle(title);
zy.setUpload(fileupload);
ZiYuanDao zyDao=new ZiYuanDao();
try {
zyDao.updateZiYuan(zy, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
LogDao lDao=new LogDao();
//刪除操做添加日誌 isDel 0是增加,1是刪除,2是修改,3是審批
User user1 =(User)request.getSession().getAttribute("userBean");
String ip=request.getLocalAddr();
try {
lDao.addLogMe("ziyuan", Integer.parseInt(id) , ip, user1.getName(), user1.getId(), 2, this.servlet.getServletContext());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return mapping.findForward("ziyuanList");
}
}
『捌』 java實現圖片上傳至伺服器並顯示,如何做
給你段代碼,是用來在ie上顯示圖片的(servlet):
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String id = request.getParameter("id");
File file = new File(getServletContext().getRealPath("/")+"out"+"/"+id+".gif");
response.setCharacterEncoding("gb2312");
response.setContentType("doc");
response.setHeader("Content-Disposition", "attachment; filename=" + new String(file.getName().getBytes("gb2312"),"iso8859-1"));
System.out.println(new String(file.getName().getBytes("gb2312"),"gb2312"));
OutputStream output = null;
FileInputStream fis = null;
try
{
output = response.getOutputStream();
fis = new FileInputStream(file);
byte[] b = new byte[1024];
int i = 0;
while((i = fis.read(b))!=-1)
{
output.write(b, 0, i);
}
output.write(b, 0, b.length);
output.flush();
response.flushBuffer();
}
catch(Exception e)
{
System.out.println("Error!");
e.printStackTrace();
}
finally
{
if(fis != null)
{
fis.close();
fis = null;
}
if(output != null)
{
output.close();
output = null;
}
}
}
這個程序的功能是根據傳入的文件名(id),來為瀏覽器返回圖片流,顯示在<img>標簽里
標簽的格式寫成如下:
<img src="http://localhost:8080/app/preview?id=111 "/><br/>
顯示的是111.gif這個圖片
你上面的問題:
1.我覺得你的第二個辦法是對的,我們也是這樣做的,需要的是把資料庫的記錄id號傳進servlet,然後讀取這條記錄中的路徑信息,生成流以後返回就是了
關於上傳文件的問題,我記得java中應該專門有個負責文件上傳的類,你調用就行了,上傳後存儲在指定的目錄里,以實體文件的形式存放
你可以參考這個:
http://blog.csdn.net/arielxp/archive/2004/09/28/119592.aspx
回復:
1.是的,在response中寫入流就行了
2.是發到servlet中的,我們一般都是寫成servlet,短小精悍,使用起來方便,struts應該也可以,只是我沒有試過,恩,你理解的很對
『玖』 用java完成圖片多張批量上傳的功能,還有就是後台的應該怎麼處理上傳的照片。
/*
*圖片上傳參數
*/
private File[] images;
private String[] imagesFileName;
private String[] imagesContentType;
加get set方法
req=ServletActionContext.getRequest();
//增加商品欄位到資料庫
Proct proct=new Proct();
ProctCategory proctCategory=null;
ProctCategoryBiz pcb=new ProctCategoryBizImpl();
System.out.println("third is:"+third_id+"ok");
if(third_id.equals("")){
proctCategory=pcb.getCategory(Integer.parseInt(second_id));
}else{
proctCategory=pcb.getCategory(Integer.parseInt(third_id));
}
proct.setCategory(proctCategory);
proct.setName(name);
proct.setPrice(Double.valueOf(price));
proct.setStock(Integer.parseInt(stock));
//上傳圖片到伺服器
String fileType = null;
String fileName = "";
if(pb.addProct(proct)){
for (int i = 0; i < images.length; i++) {
fileType = imagesFileName[i].substring(imagesFileName[i]
.lastIndexOf("."));
fileName = (new Date().getTime() + i + 1) + fileType;
File imageFile = new File(ServletActionContext.getServletContext()
.getRealPath("/files")
+ "/" + fileName);
(images[i], imageFile);
addImages("files/"+fileName);
System.out.println("路徑"+imageFile);
}
req.setAttribute("msg", "商品添加成功!");
return "success";
}else{
req.setAttribute("msg", "商品添加失敗!");
return "input";
}
『拾』 java怎麼上傳圖片
使用Commons-FileUpload 上傳文件
Struts 的文件上傳
jspSmartUpload上傳文件