java上传图片到服务器指定路径

比如jsp页面图片选择为<input name="url" class="input-large" type="file"></input>,提交之后,后台如何将图片用时间戳命名,并写到服务器的指定文件夹。
@RequestMapping(value = "gift/addGift.do")
@ResponseBody
public Map<String,Object> addGift(HttpServletRequest req,
HttpServletResponse resp) {
代码

}

        private File myFile; //文件
private String myFileContentType; //类型
private String myFileFileName;    //文件名
//。。。。getXXX() setXXX()方法

//输入流
InputStream is = new FileInputStream(myFile);
//设定文件路径
String photoPath = ServletActionContext.getServletContext()
.getRealPath("/user/photo/");
File filePhotoPath = new File(photoPath);
//判断这个路径是否存在,如果不存在创建这个路径
if (!filePhotoPath.isDirectory()) {
filePhotoPath.mkdir();
}

String extension = FilenameUtils.getExtension(this
.getMyFileFileName());   //后缀名 æ¯”如jpg
String filename = UUID.randomUUID().toString() + "." + extension;

// ç›®æ ‡æ–‡ä»¶
File tofile = new File(photoPath, filename);
// è¾“出流
OutputStream os = new FileOutputStream(tofile);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
// å…³é—­è¾“入流
is.close();
// å…³é—­è¾“出流
os.close();追问

前四行是需要建立实体类吗?还有就是提交的中的url在action中怎么获取?
  

追答

那三个变量就是action中的变量,记得要设置get set方法
struts2 会自动将那些变量初始化

下面的输入输出流可以放到execute()中
上传不了附件 不然可以直接给你看我以前写的代码

还有struts.xml 里action的配置 参考如下

/user/success.jsp
/user/showphoto.jsp
/error.jsp

image/bmp,image/pjpeg,image/gif,image/png,image/jpeg

1024*1024

追问

我用的只是spring+mybatis

追答

这个还真没用过
可以看下这个:
http://www.cnblogs.com/wuyifu/p/3627516.html

温馨提示:内容为网友见解,仅供参考
无其他回答
相似回答
大家正在搜