日期:2014-05-19  浏览次数:20808 次

求做过上传的人来啊。
例如,每个上传文件有一个file,有多个。
file的名字是它名字加1,
例如c:\\小白1,d:\\小白2,
例如有5个。我想在action中做接受做个请求怎么做?希望能附上已经成功的代码。
不知道为什么我就是拿不到它的名字?

------解决方案--------------------
package action;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class UploadAction extends ActionSupport {
private File upload; // 保存上传的文件
private String uploadContentType; // 保存上传的文件类型
private String uploadFileName; // 保存上传的文件名

public String execute() throws Exception {
// System.out.println("谁动了我的upload " + photoId);
String address = ServletActionContext.getServletContext().getRealPath(
"/");
String serverName = ServletActionContext.getRequest().getScheme()
+ "://" + ServletActionContext.getRequest().getServerName()
+ ":" + ServletActionContext.getRequest().getServerPort()
+ ServletActionContext.getRequest().getContextPath() + "/";
List<Map<String, Object>> photoAddress = this.uploadPicture(serverName,
address, 123, upload);
return SUCCESS;
}

public List<Map<String, Object>> uploadPicture(String serverName,
String address, int aaa, File upload) {
List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
// Student stu=studentInfoDao.getStudentUniqueById(id);
String imageName = aaa + ".jpg";
address = address + "images/student/" + imageName;
FileOutputStream fos = null;
InputStream is = null;
try {
fos = new FileOutputStream(address);
is = new FileInputStream(upload);
System.out.println("file length is " + upload.length());
byte[] buffer = new byte[(int) upload.length()];
int count = 0;
while ((count = is.read(buffer)) > 0) {
fos.write(buffer, 0, count);
}
// -----------------调用保存图片-----------------------
// this.savePhoto(id, buffer);
fos.close();
is.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Map<String, Object> mh = new HashMap<String, Object>();
//mh.put("id", id);
mh.put("name", serverName + "images/student/" + imageName);
list.add(mh);
return list;
}

// public File getUpload() {
// return upload;
// }

public void setUpload(File upload) {
this.upload = upload;
}

public String getUploadContentType() {
return uploadContentType;
}

public void setUploadContentType(String uploadContentType) {
this.uploadContentType = uploadContentType;
}

public String getUploadFileName() {
return uploadFileName;
}

public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}

}