save-as - 循环浏览 3 张照片并使用递增的名称保存每张照片
问题描述
我可以让它正确上传所有 1、2 或 3 个文件,输入的代码如下 -
else{
string Path = Server.MapPath("~/IncomingPhotos/" + file.FileName);
file.SaveAs(Path);
}
但我需要能够用这样的名称保存每个文件——
1.1003.IncomingPhoto1
1.1003.IncomingPhoto2
1.1003.IncomingPhoto3
1表示order_id,1003表示customer_id。
表格代码:
<table>
<tr>
<td align="center" class="auto-style2" colspan="2">
<asp:FileUpload ID="PackagingPhoto1" runat="server" Width="437px" AllowMultiple="True" />
</td>
</tr>
<tr>
<td colspan="2" align="center">
<asp:Button ID="packagingPhotos" runat="server" OnClick="packagingPhotos_Click" Text="Upload
Photos" Width="175px" />
</td>
</tr>
</table>
代码背后:
protected void packagingPhotos_Click(object sender, EventArgs e)
{
if (PackagingPhoto1.HasFile && PackagingPhoto1.PostedFiles.Count <= 3)
{
foreach (HttpPostedFile file in PackagingPhoto1.PostedFiles)
{
string extension = Path.GetExtension(file.FileName);
if (extension.ToLower() != ".jpeg" && extension.ToLower() != ".jpg" && extension.ToLower() != ".png")
{
Label9.Text = "Only files with .jpg, .jpeg, or .png extension are allowed.";
Label9.ForeColor = System.Drawing.Color.Red;
}
else
{
int photoSize = file.ContentLength;
if (photoSize > 5242880)
{
Label9.Text = "Maximum file size (5MB) exceeded!";
Label9.ForeColor = System.Drawing.Color.Red;
}
else
{
for (int i = 1; i < 3; i++)
{
string Path = Server.MapPath("~/IncomingPhotos/" + GridView1.SelectedRow.Cells[1].Text + "." + GridView1.SelectedRow.Cells[2].Text + ".ReceivingPhoto" + i + extension);
file.SaveAs(Path);
}
Label9.Text = "Photos were successfully uploaded.";
Label9.ForeColor = System.Drawing.Color.Green;
}
}
}
}
else
{
Label9.Text = "Please select at least 1 but no more than 3 files.";
Label9.ForeColor = System.Drawing.Color.Red;
}
}
解决方案
您的问题是您在错误的位置实例化您的计数器变量 (i),并且您有一个不必要的 for 循环。
第 1 步:
在 foreach 循环上方的行中声明并实例化您的计数器变量为 0。当您使用它时,将其称为比“i”更好的名称,例如“fileCounter”
if (PackagingPhoto1.HasFile && PackagingPhoto1.PostedFiles.Count <= 3)
{
int fileCounter = 0;
foreach (HttpPostedFile file in PackagingPhoto1.PostedFiles)
{
第 2 步:
摆脱 for 循环并在该位置增加一次 fileCounter。
else
{
fileCounter++;
string Path = Server.MapPath("~/IncomingPhotos/" + GridView1.SelectedRow.Cells[1].Text + "." + GridView1.SelectedRow.Cells[2].Text +
".ReceivingPhoto" + fileCounter + extension);
file.SaveAs(Path);
Label9.Text = "Photos were successfully uploaded.";
Label9.ForeColor = System.Drawing.Color.Green;
}
推荐阅读
- steam - 我可以通过用户登录获取 Steam 个人资料网址吗?
- here-api - Here Api TPEGOpenLRBase64 Code 有解码器吗?
- python - 为什么 pandas df.add_suffix() 不能与 for-loop 一起使用
- php - 将FFmpeg作为php中的进程运行时出现超时错误
- java - 如何注入 SDK 接口的新实现?
- aws-lambda - 如何在 AWS lambda 中查找当前 jar S3 位置
- javascript - 忽略特定时间的函数调用
- python - 错误:https://www (unittest.loader._FailedTest) 进行单元测试
- python-3.x - 在python中将数字的所有数字相乘
- flutter - 对两个文本小部件仅使用一次对齐