您的位置:首页 > 编程语言 > Java开发

java上传图片到文件夹

2015-10-17 22:13 686 查看
目的:上传本地图片到服务器的指定文件夹中

第一步:编写前端代码

核心代码还是用form表单提交数据,传入action中

<form id="form_picupload" action="upLoadPic.action" method="post" target="imageUpload" enctype="multipart/form-data">
<span><input type="file"  onchange="picUplod();" name="upload" id="input_file">推荐尺寸:。。。</span>
<input type="hidden" name="uploadType" id="uploadType" value="carimg" style="display: none;">
<input class="onlo" type="submit"  name="submit" value="上传" style="margin:10px 70px;"/>
</form>
<iframe id="imageUpload" name="imageUpload" src="about:blank" style="margin-left:170px;display: none;"></iframe>


iframe 中会显示上传成功后的图片预览

第二步:后台Action中的代码

// 封装上传文件域的属性
private File upload;
// 封装上传文件类型的属性
private String uploadContentType;
private String uploadType;
// 封装上传文件名的属性
private String uploadFileName;
//这里是上面一些属性的getter和setter方法。。。
//。。。
//上传图片的程序
public void upLoadPic(){
String folder = uploadType;
String loadpath = request.getSession().getServletContext().getRealPath("/") + folder; // 上传文件存放目录
if(!(new File(loadpath).isDirectory())){
new File(loadpath).mkdir();
}
FileOutputStream fos = null;
FileInputStream fis = null;
String name = "";
try {
//以服务器的文件保存地址和原文件名建立上传文件输出流
name = getUploadFileName();
fos = new FileOutputStream(loadpath + "/" + name);
//以上传文件建立一个文件上传流
fis = new FileInputStream(getUpload());
//将上传文件的内容写入服务器
byte[] buffer = new byte[1024];
int len = 0;
while ((len = fis.read(buffer)) > 0)
{
fos.write(buffer , 0 , len);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}finally{
try {
if(fos != null)
fos.close();
if(fis != null)
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
//将图片写到前端显示预览图
write("<script>parent.updatePic('" + this.contextPath + "/"+folder+"/" + name + "');</script>");
}


OK,这样就可以实现上传图片的功能了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: