Most efficient way for uploading images (two approaches)
Approach 1
This approach is the common one. If you are inserting some data containing text and images, you would upload the images before clicking Save button (saving text) .
Approach 2
I created an array of HttpPostedFile
type:
static int i;
static HttpPostedFile[] fp;
in .aspx:
<ASP:FILEUPLOAD id="btnBrowse" runat="server" />
<br />
<ASP:BUTTON id="btnUpload" runat="server" onclick="addfile_Click"/>
<br />
<ASP:BUTTON id="btnSave" runat="server" onclick="save_Click" />
btnUpload
will add the next image to the array:
protected void addfile_Click(object sender, EventArgs e)
{
if (btnBrowse.HasFile)
{
fp[i] = btnBrowse.PostedFile;
i++;
}
}
btnSave
will insert images in the array:
protected void Save_Click(object sender, EventArgs e)
{
for (int j = 0; j <= i; j++)
{
string filename = Path.GetFileName(fp[j].FileName);
var image = SD.Image.FromStream(fp[j].InputStream);
image.Save(Server.MapPath("~/images/Profile开发者_Go百科s_Images/") + filename);
}
}
It works fine. I have two questions:
- Is the second approach more efficient than the first one?
- If so, how to save the files in the array without using static (not saving values without static)? Because static is not efficient as you know.
Either way is fine, the second option is probably a bit more efficient as it uploads them all at one time rather than posting a file and then posting another. It will take the same amount of time for the server, but from the user experience, this will be tedious.
However, for a real nice user experience as well as the capability to upload multiple files at once, use uploadify: http://www.uploadify.com/
It is unclear what "efficient" mans for you. Are you concerned about beeing convinient for user (usability?), or what is fastest/most optimal for server (performance?), or correctness (which seem to be the way you've used it in "static is not efficient")...
Using static will not work if you want to support multiple users. Static is rearly reasonable in server side applications and almost never safe to store user's data for server code.
If you want to store files one by one consider using SQL session state or some other persistant storage as files saved in memory between requests could be lost due to process restart.
精彩评论