利用struts实现jsp中的图片上传和预览

本文介绍了一种使用JSP实现图片预览与上传的方法。通过整合jQuery和AjaxFileUpload插件,实现了图片的选择、预览及上传功能。文章详细展示了页面布局、JavaScript代码、配置文件以及后端Action等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

jsp代码

<input type=”file” name=”file” id=”f_UpImgId” value=”” style=”width: 200px”/>//选取图片
<input type=”button” value=”预览” id=”preBtnId”/>//预览按钮
<div id=”previewImgId” ></div>//要显示的图片
<input type=”hidden” id=”imgUrlID” name=”imgUrl” value=”sa”/>

ajax代码

$("#preBtnId").click(function(){
            $.ajaxFileUpload
            (
                {
                    url: '${url}adminjs/image!preview.action', //用于文件上传的服务器端请求地址
                    secureuri: false, //是否需要安全协议,一般设置为false
                    fileElementId: 'f_UpImgId', //文件上传域的ID
                    dataType: 'json', //返回值类型 一般设置为json
                    success: function (data, status)  //服务器成功响应处理函数
                    {
                        $("#previewImgId").html("&lt;img style='height: 100px;' src='${url}admin/image!toView.action?imgPath="+data.imgNewPath+"'/>");

                        $("#imgUrlID").val(data.imgNewPath);
                    },
                    error: function (data, status, e)//服务器响应失败处理函数
                    {

                    }
                }
            )
        });

引入头文件

<script src=”${url}lib/jquery-1.4.2.min.js” type=”text/javascript”></script>
<script src=” ${url}lib/ajaxfileupload.js” type=”text/javascript”></script>

配置文件

adminjs包下面的用来上传图片的配置文件
<action name=”image” class=”adminArticleAction”>
<interceptor-ref name=”defaultStack”>
<param name=”allowedTypes”>image/bmp,image/pjpeg,image/x-png,image/png,image/gif,image/jpg</param>
<param name=”fileUpload.maximumSize”>4MB</param>
</interceptor-ref>
<result type=”json”>
<param name=”contentType”>text/html</param>
</result>
</action>
admin包下面的用来预览图片的配置文件
<action name=”image” class=”adminArticleAction”>
<result name=”stream” type=”stream”>
<param name=”contentType”>image/jpeg</param>
<param name=”inputName”>photo</param>
</result>
</action>

action

private File file;
private InputStream photo;//预览图片
private String fileFileName;//与jsp中的对应。否则获取不到
private String fileFileContentType;
private String imgNewPath;
public InputStream getPhoto() {
return photo;
}
public void setFile(File file) {
this.file = file;
}
public void setFileFileName(String fileFileName) {
this.fileFileName = fileFileName;
}
public void setFileFileContentType(String fileFileContentType) {
this.fileFileContentType = fileFileContentType;
}
public String getImgNewPath() {
return imgNewPath;
}
//上传图片
public String preview() throws Exception{
if(file == null){
s = -101;
return SUCCESS;
}
String path = SysConfigStatic.COVER_IMAGE_UPLOAD_PATH;//要上传的目录
imgNewPath = path+adminArticleService.addImage(file, fileFileName, path);//上传图片到指定目录
return SUCCESS;
}

//预览
public String toView() throws Exception{
String imgPath=request.getParameter(“imgPath”);
System.out.println(imgPath);
File f = new File(imgPath);
photo = new FileInputStream(f);
response.setHeader(“Pragma”, “No-cache”);
response.setDateHeader(“Expires”, 0L);
response.setHeader(“Content-Length”,f.length()+”“);
return “stream”;
}

service

@Override
public String addImage(File srcFile, String oldFileName, String path) {
boolean f = false;
String suffix = oldFileName.substring(oldFileName.lastIndexOf(“.”));//获取图片后缀
String fileName = String.valueOf(new Date().getTime())+suffix;//随机生成文件名

try {
FileInputStream fis = new FileInputStream(srcFile);
FileOutputStream fos = new FileOutputStream(path+”/”+fileName);
byte[] buffer = new byte[(int)fis.available()];
fis.read(buffer);
fos.write(buffer);
f = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
f = false;
} catch (IOException e) {
e.printStackTrace();
f = false;
}
if(!f)
return “error”;
return fileName;
}

### 使用Transformer模型进行图像分类的方法 #### 方法概述 为了使Transformer能够应用于图像分类任务,一种有效的方式是将图像分割成固定大小的小块(patches),这些小块被线性映射为向量,并加上位置编码以保留空间信息[^2]。 #### 数据预处理 在准备输入数据的过程中,原始图片会被切分成多个不重叠的patch。假设一张尺寸为\(H \times W\)的RGB图像是要处理的对象,则可以按照设定好的宽度和高度参数来划分该图像。例如,对于分辨率为\(224\times 224\)像素的图像,如果选择每边切成16个部分的话,那么最终会得到\((224/16)^2=196\)个小方格作为单独的特征表示单元。之后,每一个这样的补丁都会通过一个简单的全连接层转换成为维度固定的嵌入向量。 ```python import torch from torchvision import transforms def preprocess_image(image_path, patch_size=16): transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), # 假设目标分辨率是224x224 transforms.ToTensor(), ]) image = Image.open(image_path).convert('RGB') tensor = transform(image) patches = [] for i in range(tensor.shape[-2] // patch_size): # 高度方向上的循环 row_patches = [] for j in range(tensor.shape[-1] // patch_size): # 宽度方向上的循环 patch = tensor[:, :, i*patch_size:(i+1)*patch_size, j*patch_size:(j+1)*patch_size].flatten() row_patches.append(patch) patches.extend(row_patches) return torch.stack(patches) ``` #### 构建Transformer架构 构建Vision Transformer (ViT),通常包括以下几个组成部分: - **Patch Embedding Layer**: 将每个图像块转化为低维向量; - **Positional Encoding Layer**: 添加绝对或相对位置信息给上述获得的向量序列; - **Multiple Layers of Self-Attention and Feed Forward Networks**: 多层自注意机制与前馈神经网络交替堆叠而成的核心模块; 最后,在顶层附加一个全局平均池化层(Global Average Pooling)以及一个多类别Softmax回归器用于预测类标签。 ```python class VisionTransformer(nn.Module): def __init__(self, num_classes=1000, embed_dim=768, depth=12, num_heads=12, mlp_ratio=4., qkv_bias=False, drop_rate=0.): super().__init__() self.patch_embed = PatchEmbed(embed_dim=embed_dim) self.pos_embed = nn.Parameter(torch.zeros(1, self.patch_embed.num_patches + 1, embed_dim)) self.cls_token = nn.Parameter(torch.zeros(1, 1, embed_dim)) dpr = [drop_rate for _ in range(depth)] self.blocks = nn.Sequential(*[ Block( dim=embed_dim, num_heads=num_heads, mlp_ratio=mlp_ratio, qkv_bias=qkv_bias, drop=dpr[i], ) for i in range(depth)]) self.norm = nn.LayerNorm(embed_dim) self.head = nn.Linear(embed_dim, num_classes) def forward(self, x): B = x.shape[0] cls_tokens = self.cls_token.expand(B, -1, -1) x = self.patch_embed(x) x = torch.cat((cls_tokens, x), dim=1) x += self.pos_embed x = self.blocks(x) x = self.norm(x) return self.head(x[:, 0]) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值