Как я программно сохраняю образ от URL?

Используйте низкоуровневый $.ajax() вызов:

$.ajax({
  url: "/yourservlet",
  data: { },
  complete: function(xmlHttp) {
    // xmlHttp is a XMLHttpRquest object
    alert(xmlHttp.status);
  }
});

Попытка это для перенаправления:

if (xmlHttp.code != 200) {
  top.location.href = '/some/other/page';
}
53
задан Cœur 4 April 2017 в 02:09
поделиться

2 ответа

Проще было бы написать что-то вроде этого:

WebClient webClient = new WebClient();
webClient.DownloadFile(remoteFileUrl, localFileName);
113
ответ дан 7 November 2019 в 08:23
поделиться

You just need to make a basic http request using HttpWebRequest for the URI of the image then grab the resulting byte stream then save that stream to a file.

Here is an example on how to do this...

'As a side note if the image is very large you may want to break up br.ReadBytes(500000) into a loop and grab n bytes at a time writing each batch of bytes as you retrieve them.'

using System;
using System.IO;
using System.Net;
using System.Text;

namespace ImageDownloader
{
    class Program
    {
        static void Main(string[] args)
        {
            string imageUrl = @"http://www.somedomain.com/image.jpg";
            string saveLocation = @"C:\someImage.jpg";

            byte[] imageBytes;
            HttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);
            WebResponse imageResponse = imageRequest.GetResponse();

            Stream responseStream = imageResponse.GetResponseStream();

            using (BinaryReader br = new BinaryReader(responseStream ))
            {
                imageBytes = br.ReadBytes(500000);
                br.Close();
            }
            responseStream.Close();
            imageResponse.Close();

            FileStream fs = new FileStream(saveLocation, FileMode.Create);
            BinaryWriter bw = new BinaryWriter(fs);
            try
            {
                bw.Write(imageBytes);
            }
            finally
            {
                fs.Close();
                bw.Close();
            }
        }
    }
}
30
ответ дан 7 November 2019 в 08:23
поделиться